dwyl / learn-istanbul

:checkered_flag: Learn how to use the Istanbul JavaScript Code Coverage Tool
339 stars 41 forks source link

(ES6) Missing description about branches originated by default value for function parameters #16

Open MG55 opened 6 years ago

MG55 commented 6 years ago

I'm using istanbul 0.4.5 (with istanbul-lib-coverage 1.2.0 and istanbul-lib-instrument 1.10.1) to check coverage of my jasmine unit tests over my ES6 source, and I found a branches count which is not mentioned in your document.

If my function has a default value for input parameter, like this (this is a class used to create an AngularJS service):

class UserDataService {
    getClientData() {
        return this.client;
    }
    setClientData(obj = { foo: 'bar' }) {
        this.client = obj;
    }
}
export default UserDataService;

Notice the default value for setClientData parameter obj.

If my test suite is:

import moduleUnderTesting from './userData';

describe('Service: UserDataService', () => {
    let service;

    beforeEach(() => {
        angular.mock.module(moduleUnderTesting);
    });

    beforeEach(inject((_UserDataService_) => {
        service = _UserDataService_;
    }));

    describe('method setClientData and getClientData', () => {
        it('should set/get clientData correctly', () => {
            const cData = { one: 1, two: 2 };
            service.setClientData(cData);
            expect(service.getClientData()).toBe(cData);
        });
    });
});

The test run reports 1 branch not covered:

Branch not covered

While, if I add a test case that makes setClientData use the default value for obj parameter, like this:

import moduleUnderTesting from './userData';

describe('Service: UserDataService', () => {
    let service;

    beforeEach(() => {
        angular.mock.module(moduleUnderTesting);
    });

    beforeEach(inject((_UserDataService_) => {
        service = _UserDataService_;
    }));

    describe('method setClientData and getClientData', () => {
        it('should set/get clientData correctly', () => {
            const cData = { one: 1, two: 2 };
            service.setClientData(cData);
            expect(service.getClientData()).toBe(cData);
        });

        it('should set/get clientData correctly using default value', () => {
            service.setClientData();
            expect(service.getClientData()).toEqual({ foo: 'bar' });
        });
    });
});

Test run reports full coverage:

Branch covered

This is an issue of istanbul itself, because the coverage should show what's the missing branch; anyway, I'm reporting it here as well in order for it to be pointed out in your document.