测试是否在笑话中调用了外部组件方法

时间:2018-11-16 06:37:38

标签: jestjs enzyme

我正在使用jestenzyme进行单元测试。以下是我的index.js文件。我需要测试文件的openNotificationuploadErrorNotification功能。但是,仅导出uploadErrorNotification函数。因此,我该如何测试这两个功能。

此外,除了jestenzyme之外,我不想使用任何其他libray。

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

1 个答案:

答案 0 :(得分:0)

您必须模拟外部依赖关系:

首先模拟my_object.prop.static_method(my_object),以使antd是间谍

notification.open

然后将模块导入测试中

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

知道您可以像这样使用它:

import { notification  } from 'antd';