angular - Angular 7 中订阅方法中的代码覆盖行

标签 angular testing jasmine code-coverage istanbul

我有以下代码,无法使用 Istanbul 测试红色行:

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

最佳答案

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

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

因此,当它执行测试时,它会查找条件 (response.result.httpStatus === 200) 其评估结果为 true

同样,在另一个测试中,将httpStatus添加为400,使其执行另一个 条件和监视方法 showInvalidAuthentication 并期望它被调用。

检查路由部分,

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

并将其添加到提供者中:

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

在测试中,当httpStatus200时,预期如下

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

有了上面的内容,您的测试将涵盖 110 和 113

关于angular - Angular 7 中订阅方法中的代码覆盖行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729800/

相关文章:

angular - 如何取消订阅 ngrx/store?

angular - 错误 : No provider for ShopService! 在另一个服务中使用一个服务

testing - 网络应用测试

security - 如何在 Testcafe 中隐藏密码或使用 secret ?

javascript - 我怎样才能在 Jasmine 中通过这个测试?

angular - Ionic 2 中的全局导航栏动态更改标题

angular - CKEDITOR5 - Angular8 : TypeError: this. editor.create 不是函数

c# - 用我自己的抽象 Web 服务事件

javascript - Angular Test 不调用 Promise 回调

angular - 我如何模拟 RxJs 6 计时器?