如何用Promise创建Jest模拟功能? [英] How to create Jest mock function with Promise?
本文介绍了如何用Promise创建Jest模拟功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过创建此Promise函数来模拟axios模块
I am trying to mock an axios module by create this Promise function
// __mocks__/axios.js
export default function axios() {
return new Promise((resolve) => {
resolve({ data: {} });
});
}
但是当我尝试在我的*.test.js
内部调用它时,出现此错误
But when i try to call it inside my *.test.js
, i got this error
<PortalUploadForm /> › Submit Data correctly
expect(jest.fn())[.not].toHaveBeenCalledTimes()
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function axios]
Received has type: function
Received has value: [Function axios]
87 | await wait(() => {
88 | // mockAxios.mockResponse({ data: { ...uploadPortalResult } });
> 89 | expect(mockAxios).toHaveBeenCalledTimes(1);
| ^
90 | expect(nameInput.value).toEqual(null);
91 | });
92 | });
那么我如何使用jest.fn()创建一个模拟的Promise函数呢?
So how can i make a mock promise function using jest.fn()?
谢谢!
推荐答案
您似乎正在尝试将axios
的默认导出模拟为返回已解析的Promise
的模拟函数.
It looks like you are trying to mock the default export for axios
to be a mock function that returns a resolved Promise
.
在这种情况下,您可以像这样为axios
创建模拟:
In that case you can create your mock for axios
like this:
__ mocks __/axios.js
__mocks__/axios.js
export default jest.fn(() => Promise.resolve({ data: {} }));
...并且您可以在这样的测试中使用它:
...and you can use it in a test like this:
import axios from 'axios';
const func = () => axios();
test('func', async () => {
const promise = func();
expect(axios).toHaveBeenCalledTimes(1); // Success!
await expect(promise).resolves.toEqual({ data: {} }); // Success!
})
这篇关于如何用Promise创建Jest模拟功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文