【发布时间】:2020-02-27 17:06:06
【问题描述】:
我是 jest 的新手,我正在尝试调用 await 函数以返回承诺。但我收到了错误,如预期的呼叫 1 和收到的呼叫是 0
代码:
public async callDataSourceCommand(dialogData: any, RecipeId: string) {
const gridItems = await this.dataSourceService.myPromiseMethod(id, collection);
}
模拟数据
public get dataSourceServiceMock(): any = {
return {
myPromiseMethod: function () {
return Promise.resolve({
id: '123',
collection: []
});
}
}
}
测试套件
it('1. Should execute ', async() => {
const myDialogApp: DialogApp = TestBed.get(DialogApp);
myDialogApp.selectedOrder = selectedOrder;
myDialogApp.RecipeId = Recipe.__id;
myDialogApp.callDataSourceCommand(dialogData, RecipeId);
jest.spyOn(dataSourceServiceMock, 'myPromiseMethod');
expect(dataSourceServiceMock.myPromiseMethod).toHaveBeenCalled();
});
添加了shuan的评论后,我仍然面临一个问题,
console.error node_modules/zone.js/dist/zone.js:703 未处理的承诺拒绝:位置 1 的 JSON 中的意外标记 o;区域:代理区域;任务:Promise.then;值:SyntaxError:位置 1 处 JSON 中的意外标记 o 在 JSON.parse() 在 OrderManagementMultipleBatchesDialogApp。 (D:\DCS_WorkSpace\src\DCSPlus\UI\libs\order-management\apps\src\components\order-management-multiple-batches-dialog-app\order-management-multiple-ba tches-dialog-app.factory.ts:102:30)
我已经更新了测试用例
模拟数据
public get dataSourceServiceMock(): any = {
return {
myPromiseMethod: function () {
return Promise.resolve({
selectedOrder: {
earlierStartTime: '2/5/2020',
__id: 'orderId123'
},
batchCollection: {
__id: 'b1order 1',
masterRecipeName: 'New recipe_V1.0',
plannedQuantity: '3',
masterRecipeId: 'ns=6;s=4/ProjectData/1',
actualQuantity: '1',
description: 'batchDesc',
}
});
}
}
}
测试套件
it('1. Should execute ', async() => {
const myDialogApp: DialogApp = TestBed.get(DialogApp);
myDialogApp.selectedOrder = selectedOrder;
myDialogApp.RecipeId = Recipe.__id;
jest.spyOn(dataSourceServiceMock, 'myPromiseMethod');
await myDialogApp.callDataSourceCommand(multipleBatchData, masterRecipeId);
expect(dataSourceServiceMock.myPromiseMethod).toHaveBeenCalled();
});
【问题讨论】:
-
看到一个异步函数调用很奇怪 - 即
myDialogApp.callDataSourceCommand(dialogData, RecipeId);没有等待 - 你确定你知道如何使用 async/await 吗?
标签: javascript typescript jestjs ts-jest