我有一个异步方法,我正在调用其他 2 个返回承诺的方法。我在嘲笑uploadData
并addOrEdit
返回一个已解决的承诺。当我调用 时uploadFile
,uploadData
和addOrEdit
方法都被覆盖了,但是期望,即被addOrEdit
调用失败。我正在使用带有 Jest 的 Angular 9。
这是代码:
待测方法:
async uploadFile(): Promise<void> {
let uploadedLeis: Lei[] = [];
this.onNoClick(); // closeing the upload dialog
try {
const { leis, errors } = await this._fileService.uploadData(
this.files[0],
);
try {
uploadedLeis = await this._lei.addOrEdit(leis);
if (!this._util.isEmpty(uploadedLeis)) {
this._lei.updateLocalData(uploadedLeis);
if (this._util.isEmpty(errors)) {
this._notification.notifySuccess(
`File was successfully uploaded with ${uploadedLeis.length} LEI(s)`,
);
} else {
this._notification.notifySuccess(
`File was successfully uploaded with ${uploadedLeis.length} LEI(s).\nThere were ${errors.length} errors in the file`,
'View Errors',
);
}
} else {
this._notification.notifyError(`No records were updated`);
}
} catch (err) {
this._notification.notifyError(
`Sorry!! Failed to update records from the file`,
err,
);
}
} catch (err) {
this._notification.notifyError(
`Sorry!! Problem occured while reading the file\n${err.error}`,
err,
);
} finally {
this.files = [];
}
}
测试用例
it(`test description`, fakeAsync(() => {
const spy1 = jest.spyOn(component, 'onNoClick');
const spy2 = jest.spyOn(fileService, 'uploadData').mockResolvedValue({
leis: [],
errors: [],
});
const spy3 = jest.spyOn(leiService, "addOrEdit").mockResolvedValue({});
component.fileUploaded = true;
component.files = event;
fixture.detectChanges();
component.uploadFile();
flush();
expect(spy1).toBeCalled(); // passes
expect(spy2).toBeCalled(); // passes
expect(spy3).toBeCalled(); // fails
}));