How to create Jest mock function with Promise?

后端 未结 2 1908
醉梦人生
醉梦人生 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!
    })
    

提交回复
热议问题