文件名 Postman.js
"use strict";
define([], function() {
var postManSingleton = (function() {
var postManInstance
, createPostMan = function() {
var events = {};
return {
publish: function(event, payload) {
if(!events.hasOwnProperty(event))
return;
events[event].forEach(function(listener){
listener(payload || {});
});
},
subscribe: function(event, listener) {
if(!events.hasOwnProperty(event))
events[event] = [];
var index = events[event].push(listener)-1;
return {
remove: function () {
delete events[event][index];
}
}
}
}
};
return {
getInstance: function() {
if(!postManInstance)
postManInstance = createPostMan();
return postManInstance;
}
}
}());
return postManSingleton.getInstance();
});
在 index.test.js 中导入此文件
import * as Postman from 'postman.js';
我如何 Jest 模拟它的发布和订阅事件。 我试过了
jest.mock('Postman.publish', () =>({//some code}))
错误:无法从“index.test.js”中找到模块 Postman.publish
请帮助如何模拟上述文件。有可能吗?
最佳答案
你的 Postman.js 在 AMD 中,Jest 不支持 AMD。所以你需要将 AMD 转换为 commonjs。
您可以使用 babel-plugin-transform-amd-to-commonjs用于转换。
关于javascript - 使用 import * 导入的 jest 模拟模块来测试 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47689328/