How to create Jest mock function with Promise?

后端 未结 2 1694
陌清茗
陌清茗 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:27

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

    import axios from "axios";
    
    jest.mock("axios");
    const mockAxios = axios as jest.Mocked;
    

    Then in your describe block:

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

提交回复
热议问题