在 Angular 应用程序中,有一个具有以下方法的控制器
onClick(): void {
this.http
.get('some/endpoint')
.subscribe(
(response) => {
const editUrl = this.service.composeUrl(response);
if (!editUrl) {
// want to test this error is thrown, when editUrl is null
throw Error('Cannot construct valid URL');
}
// do something else
},
() => {
// request clean up
}
);
}
我想编写 Jasmine 测试来验证,如果editUrl
无法由响应组成,将引发错误。
it('when call is successful but editUrl cannot be constructed, then error is thrown', () => {
mockHttp.get = jasmine
.createSpy()
.and.returnValue(of({}));
mockService.composeUrl= jasmine
.createSpy()
.and.returnValue(null);
expect(() => { component.onClick() }).toThrowError();
});
我的测试失败了:
错误:预期函数会抛出错误。
但我也在浏览器控制台中看到抛出了错误Uncaught Error: Cannot construct valid URL
我认为问题在于,在 http observable 的下一个处理程序中抛出了错误,并且以某种方式耗尽了 jasmine 上下文。
我可以通过将匿名下一个处理程序提取到命名函数中并直接测试该函数来修复它,但我更喜欢使用匿名箭头函数进行订阅。
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)