![](/img/trans.png)
[英]Angular 9 + jest : unit test, mock a promise and check method called then
[英]Angular - mock Promise method for Jasmine unit test
public onSubmit(registerData: RegisterDataModel): void {
this.registrationService.registerWithEmailAndPassword(registerData).then((msg: string[]) =>
this.router.navigate(['/completeSignUp']).then(() => {
msg.forEach(singleMessage => this.notificationService.primary(singleMessage));
}))
.catch((msg) => msg.forEach(singleMessage => {
this.notificationService.danger(singleMessage);
}));
}
我想測試是否在我的方法中調用了router.navigate
。 現在我想模擬我的service.registerWithEmailAndPasswort
Promise 但不知何故我無法模擬它。
//Stubs
const routerStub: Router = jasmine.createSpyObj('Router', ['navigate']);
const registryStub: RegistrationService = jasmine.createSpyObj('RegistrationService', ['registerWithEmailAndPassword']);
it('should navigate on promise - success', () => {
(<jasmine.Spy>registryStub.registerWithEmailAndPassword).and.callThrough();
const spy = (<jasmine.Spy>routerStub.navigate);
component.onSubmit({username: null, email: null, password: null, passwordConfirm: null, termsAndCondition: null});
expect(spy).toHaveBeenCalledWith(['/completeSignUp']);
});
出現的錯誤是: TypeError: Cannot read property 'then' of undefined
人如何正確模擬此服務?
我也試圖嘲笑這樣的承諾:
(<jasmine.Spy>registryStub.registerWithEmailAndPassword)
.and.returnValue(new Promise(() => Promise.resolve()));
但它仍然讓我覺得:
Expected spy Router.navigate to have been called with [ [ '/completeSignUp' ] ] but it was never called.
正如硅靈魂所提到的,您肯定需要使用返回值模擬router.navigate
承諾,否則它將進入Promise.reject()
。 通過添加(<jasmine.Spy>routerStub.navigate).and.returnValue(Promise.resolve());
單元測試應該沒問題。 最終的單元測試應如下所示:
it('should navigate on promise - success', fakeAsync(() => {
const spy = (<jasmine.Spy>routerStub.navigate).and.returnValue(Promise.resolve());
(<jasmine.Spy>registryStub.registerWithEmailAndPassword).and.returnValue(Promise.resolve(['test']));
component.onSubmit({username: 'test', email: 'test', password: 'test', passwordConfirm: 'test', termsAndCondition: true});
tick();
expect(spy).toHaveBeenCalledWith(['/completeSignUp']);
}));
您將收到錯誤消息,因為 registerWithEmailAndPassword 間諜不返回 Promise。 您可以使用 callFake 返回一個 Promise:
(<jasmine.Spy>registryStub.registerWithEmailAndPassword).and.callFake(() => Promise.resolve([]));
此外,promise 是異步的,因此您可能應該使用fakeAsync測試和滴答,或超時或使用then方法而不是 Promise 返回對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.