【发布时间】:2018-07-27 14:42:39
【问题描述】:
测试方法
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.
【问题讨论】:
标签: angular unit-testing jasmine mocking karma-jasmine