我在写单元测试对每个单独的模块,我有。其中一个模块是一个命令队列(缓解脚本的异步加载):
在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);
});
});
});
运行测试时我收到此错误信息:
类型错误:无法读取的未定义的属性“CMD”
这个错误对在cmd.js的iife参数指向文件:}(window.advert.cmd || []));
我首先想到它与需要被重新命名为全球(测试中),但即使不改变错误消息的窗口对象做。有任何想法吗?
谢谢
创建像prepare-environement.js
文件
global.advert = {};
global.advert.cmd = [];
和cmd.js
之前导入
import './prepare-environement'
import cmd from './../src/utils/cmd';