无法通过Jest加载AMD模块

时间:2015-11-24 09:18:12

标签: requirejs amd jestjs

我正在尝试使用Jest对我的React代码进行单元测试,但我也使用requirejs,所以我的所有React代码都在AMD模块中。它显然在浏览器中运行良好,但是当我运行Jest测试时,它无法加载我的AMD模块。 最初它给我定义说define is not defined的错误,所以我使用了需要修复它的amdefine。现在它可以理解define但仍然无法加载我的模块。

3 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,所以我继续在测试文件的顶部嘲笑我的依赖:

jest.mock('../../components/my-button', () => {
  // mock implementation
})

import MyButton from '../../components/my-button';

这样,当加载MyButton时,它的依赖关系已被模拟,因此它不会尝试加载RequireJS模块。

答案 1 :(得分:1)

Jest还没有正式的Facebook支持requirejs。但是有计划的。看这个帖子: https://github.com/facebook/jest/issues/17

同样在这个帖子中,Sterpe发布了一个他写的插件来做(但我没试过): https://github.com/sterpe/jest-requirejs

答案 2 :(得分:0)

我今天遇到了同样的问题,这就是我所做的:

Module.js

(()=> {
    const dependencies = ['./dep.js'];
    const libEnv = function (dep) {

        // lib content
        function theAnswer (){
            return dep.answer;
        }

        return {theAnswer}; // exports

    };
    //AMD & CommonJS compatibility stuff
    // CommonJS
    if (typeof module !== 'undefined' && typeof require !== 'undefined'){
        module.exports = libEnv.apply(this, dependencies.map(require));
        module.exports.mockable = libEnv; // module loader with mockable dependencies
    }
    // AMD
    if (typeof define !== 'undefined') define(dependencies, libEnv);
})();

您将在my github repository上找到所有需要的文件进行测试:

    浏览器中的
  • for requirejs

  • 带有节点for jest

https://github.com/1twitif/testRequireJSAmdModulesWithJest

相关问题