1

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();
}));
0

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.