测试是否在jest中调用外部组件方法

vfh0ocws  于 2023-02-06  发布在  Jest
关注(0)|答案(2)|浏览(217)

我正在使用jestenzyme进行单元测试。下面是我的index.js文件。我需要测试文件的openNotificationuploadErrorNotification函数。但是,只有uploadErrorNotification函数被导出。那么,我如何测试这两个函数呢?
此外,除了jestenzyme之外,我不想使用任何其他库。

//index.js
import {
      notification
    } from 'antd';

    const openNotification = (message, description, className) => {
      notification.open({
        key: 'upload-template',
        message,
        description,
        placement: "bottomRight",
        duration: null,
      });
    };

    const uploadErrorNotification = (uploadFailedText, errorMsg) => {
      openNotification(uploadFailedText, errorMsg, 'error');
    };

    export {
      uploadErrorNotification
    }

这是我的测试文件:

//test.js

import { uploadErrorNotification } from '../index.js

jest.mock('notification', () => ({ open: () => jest.fn() })); // was trying this but I couldn't understand how it will work

describe('Notification validation functions testing', () => {
  uploadErrorNotification('Upload failed', 'Something went wrong.');
  expect("openNotification").toHaveBeenCalledTimes(1); // want to do something like this
});
eufgjt7s

eufgjt7s1#

你不得不嘲笑外部依赖:
首先模拟antd,使notification.open成为间谍

jest.mock('antd', () => ({notification: open: {jest.fn()}}))

然后将模块导入到测试中

import { notification  } from 'antd';

知道你可以这样使用它:

expect(notification.open).toHaveBeenCalledTimes(1);
6l7fqoea

6l7fqoea2#

如果你想在不覆盖其他antd组件的情况下测试通知,你可以添加jest.requireActual('antd ')。

jest.mock('antd', () => {
      return {
        ...jest.requireActual('antd'),
        notification: {
          open: jest.fn(),
        },
      };
    });

相关问题