How to create Jest mock function with Promise?

后端 未结 2 1685
陌清茗
陌清茗 2021-02-15 08:06

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:42

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

提交回复
热议问题