Varis Darasirikul
Varis Darasirikul

Reputation: 4177

How to create Jest mock function with Promise?

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!

Upvotes: 59

Views: 176076

Answers (2)

gerald
gerald

Reputation: 221

In my tests, I usually just mock axios like this:

import axios from "axios";

jest.mock("axios");
const mockAxios = axios as jest.Mocked<typeof axios>;

Then in your describe block:

beforeEach(() => {
  mockAxios.request.mockImplementationOnce(
    (): Promise<any> => Promise.resolve({ hello: "world" })
  );
});

Upvotes: 7

Brian Adams
Brian Adams

Reputation: 45810

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!
})

Upvotes: 74

Related Questions