如何使用 Promise 创建 Jest 模拟功能? [英] How to create Jest mock function with Promise?

查看:37
本文介绍了如何使用 Promise 创建 Jest 模拟功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过创建这个 Promise 函数来模拟 axios 模块

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

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

但是当我尝试在我的 *.test.js 中调用它时,我收到了这个错误

But when i try to call it inside my *.test.js, i got this error

<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() 制作一个模拟承诺函数?

So how can i make a mock promise function using jest.fn()?

谢谢!

推荐答案

看起来您正在尝试将 axios 的默认导出模拟为返回已解析 Promise 的模拟函数.

It looks like you are trying to mock the default export for axios to be a mock function that returns a resolved Promise.

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

In that case you can create your mock for axios like this:

__mocks__/axios.js

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

这篇关于如何使用 Promise 创建 Jest 模拟功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆