Jest iife 模块测试 - window 变量未定义
Jest iife module testing - window variable not defined
我正在为每个单独的模块编写单元测试。其中一个模块是命令队列(以简化脚本的异步加载):
在html头:
<script>
var advert = advert || {};
advert.cmd = advert.cmd || [];
</script>
cmd.js:
let cmd = (function(cmd) {
const queue = cmd;
function _init() {
while(queue.length > 0) {
_next();
}
}
function _next() {
queue.shift().call();
}
function _push(fn) {
console.log('pushing', fn);
if (!fn instanceof Function) {
throw Error('core.cmd - argument not of type Function');
}
queue.push(fn);
_next();
}
return {
'init': _init,
'queue': queue,
'push': _push
}
}(window.advert.cmd || []));
export default cmd;
至于我的单元测试,我有以下内容:
import cmd from './../src/utils/cmd';
beforeAll(() => {
global.advert = {};
global.advert.cmd = [];
});
describe('Given we use a queue', () => {
let functionResult;
beforeEach(() => {
functionResult = 0;
});
describe('When the queue is initialized', () => {
test('It should execute the already contained functions ', () => {
global.advert.cmd = [
function(){functionResult++},
function(){functionResult++}
];
global.advert.cmd = cmd;
global.advert.cmd.init();
expect(functionResult).toBe(2);
});
});
});
当运行测试时我得到这个错误信息:
TypeError: Cannot read property 'cmd' of undefined
此错误指向 cmd.js 文件中的 iife 参数:}(window.advert.cmd || []));
我首先认为它与需要重命名为全局(在测试中)的 window 对象有关,但即使这样也不会改变错误消息。有任何想法吗?
谢谢
创建类似 prepare-environement.js
的文件
global.advert = {};
global.advert.cmd = [];
并在 cmd.js
之前导入
import './prepare-environement'
import cmd from './../src/utils/cmd';
我正在为每个单独的模块编写单元测试。其中一个模块是命令队列(以简化脚本的异步加载):
在html头:
<script>
var advert = advert || {};
advert.cmd = advert.cmd || [];
</script>
cmd.js:
let cmd = (function(cmd) {
const queue = cmd;
function _init() {
while(queue.length > 0) {
_next();
}
}
function _next() {
queue.shift().call();
}
function _push(fn) {
console.log('pushing', fn);
if (!fn instanceof Function) {
throw Error('core.cmd - argument not of type Function');
}
queue.push(fn);
_next();
}
return {
'init': _init,
'queue': queue,
'push': _push
}
}(window.advert.cmd || []));
export default cmd;
至于我的单元测试,我有以下内容:
import cmd from './../src/utils/cmd';
beforeAll(() => {
global.advert = {};
global.advert.cmd = [];
});
describe('Given we use a queue', () => {
let functionResult;
beforeEach(() => {
functionResult = 0;
});
describe('When the queue is initialized', () => {
test('It should execute the already contained functions ', () => {
global.advert.cmd = [
function(){functionResult++},
function(){functionResult++}
];
global.advert.cmd = cmd;
global.advert.cmd.init();
expect(functionResult).toBe(2);
});
});
});
当运行测试时我得到这个错误信息:
TypeError: Cannot read property 'cmd' of undefined
此错误指向 cmd.js 文件中的 iife 参数:}(window.advert.cmd || []));
我首先认为它与需要重命名为全局(在测试中)的 window 对象有关,但即使这样也不会改变错误消息。有任何想法吗?
谢谢
创建类似 prepare-environement.js
global.advert = {};
global.advert.cmd = [];
并在 cmd.js
import './prepare-environement'
import cmd from './../src/utils/cmd';