Rasshu
Rasshu

Reputation: 1799

Code coverage lines inside subscribe method in Angular 7

I have the following code and cannot test the lines in red, using Istanbul:

Istanbul code coverage snippet

The test is the following, but no error is detected:

it('should set user info JSON to local storage after successful authentication', async(() => {
    component.loginForm.get('username').setValue('test');
    component.loginForm.get('passwd').setValue('test');

    spyOn(loginService, 'postLogin').and.returnValues(of({}));

    component.sendLoginForm();

    expect(component.loginFormSuccess).toEqual(true);
    expect(component.loginFormFail).toEqual(false);

    component.loggedInUserJSON = '{"login":"test","password":"test"}';
    localStorage.setItem('loggedInUserJSON', component.loggedInUserJSON);
    fakeLocalStorage.setItem('loggedInUserJSON', component.loggedInUserJSON);

    expect(localStorage.getItem('loggedInUserJSON')).toBe(component.loggedInUserJSON);
    expect(fakeLocalStorage.getItem('loggedInUserJSON')).toBe(component.loggedInUserJSON);

    expect(component.loggedInUserJSON).toBe('{"login":"test","password":"test"}');

    expect(component.postLoginObservable).toBeTruthy();
}));

Upvotes: 1

Views: 2342

Answers (1)

dileepkumar jami
dileepkumar jami

Reputation: 2265

When you spy on the service, return the below as inside the subscribe, it is looking for it:

 spyOn(loginService, 'postLogin').and.returnValues(of({
  result : {
     httpStatus : 200
  }
}));

So, when it performs the test, it will look for the condition (response.result.httpStatus === 200) which evalutes to true

Similarly, in another test, add the httpStatus as 400 so that it executes the other condition and spy on the method showInvalidAuthentication an expect it to be called.

To check the routing part,

let routerStub = { navigate: jasmine.createSpy('navigate') };

And add it in the providers:

providers: [{ provide: Router, useValue: routerStub }]

In the test, when the httpStatus is 200, expect the below

 expect(routerStub.navigate).toHaveBeenCalledWith(['/home']);

With the above, your tests will cover lines 110 & 113

Upvotes: 2

Related Questions