我正在尝试使用 Jest 和酶解决承诺后测试这些方法。我的组件/功能代码:
// Functional Code
let functionAfterAsync = () => {
console.log('functionAfterAsync called');
}
const asyncFunction = () => {
return new Promise(resolve => resolve());
}
const functionWithAsyncCode = () => {
// ... some more code here
console.log('functionWithAsyncCode');
asyncFunction().then((res: any) => {
functionAfterAsync();
})
}
Run Code Online (Sandbox Code Playgroud)
我的测试:
functionAfterAsync = jest.fn();
// Tests
describe('<Async Test />', () => {
it('Call function after promise', () => {
functionWithAsyncCode();
expect(functionAfterAsync).toBeCalled();
})
});
Run Code Online (Sandbox Code Playgroud)
但是functionAfterAsync没有被调用,我得到的错误是:
expect(jest.fn()).toBeCalled() Expected mock function to have been called.
有没有办法做到这一点。谢谢您的帮助!!!
在断言已调用之前,您需要等待Promise解决functionAfterAsync。
最简单的方法是返回Promisefrom functionWithAsyncCode:
const functionWithAsyncCode = () => {
console.log('functionWithAsyncCode');
return asyncFunction().then(() => { // return the Promise
functionAfterAsync();
})
}
Run Code Online (Sandbox Code Playgroud)
it('Call function after promise', async () => { // use an async test function
await functionWithAsyncCode(); // wait for the Promise to resolve
expect(functionAfterAsync).toBeCalled(); // SUCCESS
})
Run Code Online (Sandbox Code Playgroud)
或者,您可以在 a 中断言.then并从您的测试函数中返回Promise:
it('Call function after promise', () => {
return functionWithAsyncCode().then(() => { // return the Promise
expect(functionAfterAsync).toBeCalled(); // SUCCESS
});
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1267 次 |
| 最近记录: |