我目前在使用带有 promise 的 Jasmine 测试时遇到问题。
错误是“Unhandled Promise rejection:”,我想这意味着我的 promise 没有正确处理 catch()
和 then()
。
这是我的测试:
it('tests the openRepo function with changed and invalid path', (done) => {
const OldPath = '/old';
const NewPath = '/invalid';
const ProjectModalBoolean = true;
component.path = OldPath;
component.openFolder = NewPath;
component.projectModalLoading = ProjectModalBoolean;
component.openRepo().then(() => {
expect(component.openFolder).toBe('');
expect(component.projectModalLoading).toBeFalsy();
done();
});
});
在函数 openRepo
中,我有以下代码:
return this.gitService.setPath(this.openFolder)
.then((data) => {
this.projectModalLoading = false;
this.projectModalVisible = false;
this.openFolder = '';
this.toastr.info(data.message, data.title);
})
.catch((data) => {
this.projectModalLoading = false;
this.openFolder = '';
this.toastr.error(data.message, data.title);
});
...调用函数:
async setPath(newPath) {
new Promise<ServiceResult>((resolve, reject) => {
if (newPath === '/new') {
resolve(new Object());
} else {
reject(new Object());
}
});
}
setPath
中的 reject()
似乎是问题所在,因为另一个通过 resolve()
的测试工作得很好
欢迎任何帮助
最佳答案
您在 setPath
方法上有 Promise
、resolve
和 reject
。而不是 catch
子句使用第二个参数回调,如下所示。
return this.gitService.setPath(this.openFolder)
.then((data) => {
this.projectModalLoading = false;
this.projectModalVisible = false;
this.openFolder = '';
this.toastr.info(data.message, data.title);
},
(data) => {
this.projectModalLoading = false;
this.openFolder = '';
this.toastr.error(data.message, data.title);
});
阅读此 article
关于angular - 单元测试和 Angular 未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858341/