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: {} });
});
}
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 | });
So how can i make a mock promise function using jest.fn()?
Thanks!
We call jest. mock('../request') to tell Jest to use our manual mock. it expects the return value to be a Promise that is going to be resolved. You can chain as many Promises as you like and call expect at any time, as long as you return a Promise at the end.
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.
In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.
The simplest and most common way of creating a mock is jest. fn() method. If no implementation is provided, it will return the undefined value. There is plenty of helpful methods on returned Jest mock to control its input, output and implementation.
It looks like you are trying to mock the default export for axios
to be a mock function that returns a resolved Promise
.
In that case you can create your mock for axios
like this:
__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!
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With