我有以下代码,无法使用 Istanbul 测试红色行:
测试如下,但没有检测到错误:
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 }]
在测试中,当httpStatus
为200
时,预期如下
expect(routerStub.navigate).toHaveBeenCalledWith(['/home']);
有了上面的内容,您的测试将涵盖 110 和 113
关于angular - Angular 7 中订阅方法中的代码覆盖行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729800/