我是开玩笑的新手,我正试图调用await函数以返回诺言。但是我收到了错误消息,如预期的呼叫1和已接的呼叫为0
代码:
public async callDataSourceCommand(dialogData: any, RecipeId: string) {
const gridItems = await this.dataSourceService.myPromiseMethod(id, collection);
}
MockData
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 未处理的承诺拒绝:JSON中位于位置1的意外令牌o;区域:ProxyZone;任务: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)
我已经更新了测试用例
MockData
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();
});
答案 0 :(得分:2)
正如Jaromanda正确编写的那样,您需要await
异步方法。同样,您需要在执行操作之前而不是执行操作之后监视该方法。
这是您可以在Jest中运行的原始示例的简化独立版本。
class MyDialogApp {
constructor(private dataSourceService: any) {}
public async callDataSourceCommand() {
await this.dataSourceService.myPromiseMethod();
}
}
const dataSourceServiceMock = {
myPromiseMethod: function() {
return Promise.resolve({
id: '123',
collection: []
});
}
};
const myDialogApp = new MyDialogApp(dataSourceServiceMock);
it('1. Should execute ', async () => {
// arrange
jest.spyOn(dataSourceServiceMock, 'myPromiseMethod');
// act
await myDialogApp.callDataSourceCommand();
// assert
expect(dataSourceServiceMock.myPromiseMethod).toHaveBeenCalled();
});