【发布时间】:2017-11-11 06:36:14
【问题描述】:
我有一个组件单元测试,它没有按我预期的方式处理来自模拟的承诺拒绝。
我在一个组件上有这个函数,它向addUserToOrganisation 发送一些数据并处理它返回的 Promise:
public onSubmit() {
this.saveStatus = 'Saving';
this.user = this.prepareSaveUser();
this._userService.addUserToOrganisation(this.user)
.then(() => this._router.navigate(['/profile']))
.catch(error => this.reportError(error));
}
在测试这个组件时,我为 UserService 提供了一个模拟,它监视 addUserToOrganisation 端点并返回某种 Promise:
mockUserService = jasmine.createSpyObj('mockUserService', ['getOrgId', 'addUserToOrganisation']);
mockUserService.getOrgId.and.returnValue(Promise.resolve('an id'));
mockUserService.addUserToOrganisation.and.returnValue(Promise.resolve());
这适用于快乐路径(解决) - 我可以测试 this._router.navigate() 是否被调用,依此类推。这是这条幸福之路的通过测试:
it('should navigate to /profile if save is successful', fakeAsync(() => {
fixture.detectChanges();
tick();
fixture.detectChanges();
component.userForm.controls['firstName'].setValue('John');
component.userForm.controls['lastName'].setValue('Doe');
component.userForm.controls['email'].setValue('j.d@gmail.com');
component.onSubmit();
tick();
fixture.detectChanges();
expect(mockRouter.navigate).toHaveBeenCalledWith(['/profile']);
}));
但是,我在测试“悲伤”路径时遇到了麻烦。我更改了我的模拟以返回一个 Promise.reject,虽然我在 onSubmit 中有一个 .catch,但我收到了这个错误:
Error: Uncaught (in promise): no
所以这很令人困惑。这是我对这条悲伤道路的测试。请注意,我更改了模拟调用的响应。
it('should show Failed save status if the save function fails', fakeAsync(() => {
mockUserService.addUserToOrganisation.and.returnValue(Promise.reject('no'));
fixture.detectChanges();
tick();
fixture.detectChanges();
component.userForm.controls['firstName'].setValue('John');
component.userForm.controls['lastName'].setValue('Doe');
component.userForm.controls['email'].setValue('j.d@gmail.com');
component.onSubmit();
tick();
fixture.detectChanges();
expect(component.saveStatus).toEqual('Failed! no');
}));
有人有什么想法吗?
【问题讨论】:
标签: javascript angular unit-testing promise angular-components