Jestjs 测试是否在jest中调用外部组件方法
我正在使用Jestjs 测试是否在jest中调用外部组件方法,jestjs,enzyme,Jestjs,Enzyme,我正在使用jest和enzyme进行单元测试。下面是我的index.js文件。我需要测试文件的openNotification和uploadErrorNotification功能。但是,仅导出uploadErrorNotification函数。那么,如何测试这两个函数呢 此外,除了jest和enzyme之外,我不想使用任何其他图书馆 //index.js import { notification } from 'antd'; const openNotificat
jest
和enzyme
进行单元测试。下面是我的index.js
文件。我需要测试文件的openNotification
和uploadErrorNotification
功能。但是,仅导出uploadErrorNotification
函数。那么,如何测试这两个函数呢
此外,除了jest
和enzyme
之外,我不想使用任何其他图书馆
//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
});
你必须模仿外部依赖性: 第一个mock
antd
,这样notification.open
就是间谍
jest.mock('antd', () => ({notification: open: {jest.fn()}}))
然后将模块导入到测试中
import { notification } from 'antd';
我知道你可以这样使用它:
expect(notification.open).toHaveBeenCalledTimes(1);
jest.fn()值必须是模拟函数或间谍。
获取此错误我已在同一测试文件中添加了jest.mock('antd',()=>({notification:{open:jest.fn()}}}))
。