我是开玩笑的新手,我正试图调用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();
});
正如Jaromanda正确编写的,您需要await
异步方法。同样,您需要在执行操作之前而不是执行操作之后监视该方法。这是一个您可以直接运行的示例。
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();
});