Angular 7中的subscribe方法中的代码覆盖行

问题描述 投票:1回答:1

我有以下代码,无法使用伊斯坦布尔测试红色线条:

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();
}));
angular testing jasmine code-coverage istanbul
1个回答
1
投票

当你监视服务时,在订阅内部返回以下内容,它正在寻找它:

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

因此,当它执行测试时,它将查找条件qazxsw poi,其值为true

类似地,在另一个测试中,将httpStatus添加为400,以便它执行另一个条件并监视方法(response.result.httpStatus === 200)并期望它被调用。

要检查路由部分,

showInvalidAuthentication

并将其添加到提供程序中:

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

在测试中,当providers: [{ provide: Router, useValue: routerStub }] httpStatus时,期待以下

200

有了上述内容,您的测试将涵盖 expect(routerStub.navigate).toHaveBeenCalledWith(['/home']);

© www.soinside.com 2019 - 2024. All rights reserved.