How to create Jest mock function with Promise?

后端 未结 2 1906
醉梦人生
醉梦人生 2021-02-15 08:20

I am trying to mock an axios module by create this Promise function

// __mocks__/axios.js
export default function axios() {
  return new Promise((resolve) =>          


        
相关标签:
2条回答
  • 2021-02-15 08:24

    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!
    })
    
    0 讨论(0)
  • 2021-02-15 08:28

    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" })
      );
    });
    
    0 讨论(0)
提交回复
热议问题