Angular 抛出错误的 jasmine SpyOn 服务调用使测试失败
Angular jasmine SpyOn service call that throws an error makes the test fail
我想从我的组件中测试以下方法:
mymethod() {
this.myservice.dostuff().subscribe((data: any) => {
console.log(data)
this.passed= true
}, err => {
console.log(err)
this.passed= false
})
}
这是我写的测试:
it('if error thrown', fakeAsync(() => {
spyOn(myservice, "dostuff").and.throwError("error");
fixture.detectChanges()
component.mymethod()
tick(1)
expect(myservice.dostuff).toHaveBeenCalled();
expect(myservice.dostuff).toThrowError("error");
expect(component.passed).toBe(false);
flush()
}));
但我一定是遗漏了一些东西,因为当我 运行 测试时,它失败并显示以下消息:
MyComponent 登录失败
错误:错误
您应该使用 throwError 模拟您的服务遇到异常时发生的情况。这将触发您预期的错误回调。
您的服务应 return 可观察。正如您目前所写,该服务没有 returning 任何东西 - 它只是抛出一个异常。通过使用 throwError
和 returnValue
你 return 一个立即抛出的可观察对象,它触发了预期的回调。
spyOn(myservice, 'dostuff').and.returnValue(throwError('someError'));
我想从我的组件中测试以下方法:
mymethod() {
this.myservice.dostuff().subscribe((data: any) => {
console.log(data)
this.passed= true
}, err => {
console.log(err)
this.passed= false
})
}
这是我写的测试:
it('if error thrown', fakeAsync(() => {
spyOn(myservice, "dostuff").and.throwError("error");
fixture.detectChanges()
component.mymethod()
tick(1)
expect(myservice.dostuff).toHaveBeenCalled();
expect(myservice.dostuff).toThrowError("error");
expect(component.passed).toBe(false);
flush()
}));
但我一定是遗漏了一些东西,因为当我 运行 测试时,它失败并显示以下消息: MyComponent 登录失败 错误:错误
您应该使用 throwError 模拟您的服务遇到异常时发生的情况。这将触发您预期的错误回调。
您的服务应 return 可观察。正如您目前所写,该服务没有 returning 任何东西 - 它只是抛出一个异常。通过使用 throwError
和 returnValue
你 return 一个立即抛出的可观察对象,它触发了预期的回调。
spyOn(myservice, 'dostuff').and.returnValue(throwError('someError'));