Search code examples
jasminekarma-jasminekarma-coveragejasmine2.0

How to cover all lines of a function with jasmine-karma


How can I cover all lines of the function below using jasmine?

   addUser(): void {
    if (this.validateNewUser()) {

        this.newUser._Job = this.selectedJob;
        this.newUser.PositionId = this.selectedJob.Id;
        this.newUser.Position = this.selectedJob.Value;

        this.newUser._Area = this.selectedArea;
        this.newUser.AreaId = this.selectedArea.Id;
        this.newUser.Area = this.selectedArea.Value;

        this.users.push(this.newUser);
        this.clear();
        this.toastService.open('Usuário incluído com sucesso!', { type: 'success', close: true });
    }
}

I am currently trying as follows, but no line is being considered covered:

    it('Given_addUser_When_UserStepIsCalled_Then_ExpectToBeCalled', (done) => {
        component.addUser = jasmine.createSpy();           
        component.addUser();
        expect(component.addUser).toHaveBeenCalled();
        done();
    });

EDITED

Now: Image here


Solution

  • There is no need to check if the method under test (addUser) has been called if you explicitly call it. You should however check if the method did what it was supposed to do. You may want to know if the toast gets displayed. Therefore, you could rewrite the test as follows.

    it('#addUser should display toast', () => {
    
        // given
        spyOn(toastService, 'open');
    
        // when
        component.addUser();
    
        // then
        expect(toastService.open).toHaveBeenCalled();
    });