Prasadau
Prasadau

Reputation: 61

Angular 2 Unit Test for IF condition

I am new to unit testing. I am trying to unit test the if condition for the code below:

hide() {
        this.count --;
        if (this.count === 0) {
            this.loaderIs = false;
        }
    }

I am trying to use spy function on loaderIs variable.

it('hide function check', () => {
        expect(loaderService.hide).toBeDefined();
        spyOn(loaderService, 'loaderIs');
        loaderService.hide();
        expect(loaderService.loaderIs).toHaveBeenCalled();
    });

Any input and guides are highly appreciated.

Upvotes: 1

Views: 15198

Answers (1)

Nodarii
Nodarii

Reputation: 974

the thing is that you should not mock unit your are testing. (in your case it is hide method). Call of hide method should call actual method. Please see code below

describe('Some test: ', () => {
    beforeEach(() => {
        loaderService.loaderIs = false;
        // ...
    });

    it('loaderIs should be falsy', () => {
        loaderService.count = 1
        loaderService.hide();
        expect(loaderService.loaderIs).toBeFalsy();
    });

    it('loaderIs should be truthy', () => {
        loaderService.count = 2
        loaderService.hide();
        expect(loaderService.loaderIs).toBeTruthy();
    });
});

Upvotes: 3

Related Questions