【问题标题】:Jest iife module testing - window variable not definedJest iife 模块测试 - 未定义窗口变量
【发布时间】:2019-02-05 13:40:00
【问题描述】:

我正在为我拥有的每个单独的模块编写单元测试。其中一个模块是命令队列(以简化脚本的异步加载):

在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: 无法读取未定义的属性“cmd”

此错误指向 cmd.js 文件中的 iife 参数:}(window.advert.cmd || []));

我首先认为它与需要重命名为全局(在测试中)的窗口对象有关,但即使这样也不会改变错误消息。有任何想法吗?

谢谢

【问题讨论】:

    标签: javascript jestjs iife


    【解决方案1】:

    创建一个类似prepare-environement.js的文件

    global.advert = {};
    global.advert.cmd = [];
    

    cmd.js之前导入

    import './prepare-environement'
    import cmd from './../src/utils/cmd';
    

    【讨论】:

    • 伟大而简单的解决方案。谢谢!我应该想到的 ;)
    猜你喜欢
    • 2018-02-26
    • 2015-04-04
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多