gpt4 book ai didi

Angular - 用于 Jasmine 单元测试的模拟 Promise 方法

转载 作者:太空狗 更新时间:2023-10-29 17:14:03 25 4
gpt4 key购买 nike

测试方法

  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有人知道如何正确模拟此服务吗?

编辑

我也试过像这样 mock 这个 promise :

    (<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.

最佳答案

正如 silicon Soul 提到的,您肯定需要模拟 router.navigate promise 返回值,否则它将进入 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']);
}));

关于Angular - 用于 Jasmine 单元测试的模拟 Promise 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51560358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com