Линии покрытия кода внутри метода подписки в Angular 7 - PullRequest
0 голосов
/ 17 февраля 2019

У меня есть следующий код, и я не могу проверить строки в красном, используя Стамбул:

Istanbul code coverage snippet

Тест следующий, но ошибки нетобнаружено:

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

1 Ответ

0 голосов
/ 17 февраля 2019

Когда вы шпионите за услугой, верните ниже, как внутри подписки, она ищет:

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

Итак, когда она выполняет тест, она будет искать условие (response.result.httpStatus === 200)значение которого равно true

Аналогично, в другом тесте добавьте httpStatus как 400, чтобы он выполнял другое условие, и следите за методом showInvalidAuthentication и ожидайте его вызова.

Чтобы проверить часть маршрутизации,

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

И добавить ее в Prividers:

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

В тесте, когда httpStatus равно 200, ожидайте ниже

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

С учетом вышеизложенного ваши тесты будут охватывать строки 110 & 113

...