如何用Promise创建Jest模拟功能?

时间:2019-05-24 03:37:29

标签: javascript promise mocking jestjs

我正在尝试通过创建此Promise函数来模拟axios模块

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

但是当我尝试在*.test.js内部调用它时,出现此错误

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

那么我如何使用jest.fn()创建一个模拟的Promise函数呢?

谢谢!

2 个答案:

答案 0 :(得分:2)

您似乎正在尝试将axios的默认导出模拟为返回已解析的Promise的模拟函数。

在这种情况下,您可以像这样为axios创建模拟:

__ mocks __ / axios.js

export default jest.fn(() => Promise.resolve({ data: {} }));

...,您可以在这样的测试中使用它:

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

答案 1 :(得分:0)

在测试中,我通常只是像这样模拟axios:

import axios from "axios";

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

然后在您的describe块中:

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