“未定义".测试带有RequireJS依赖的es6模块时在Jest中 [英] "Define is not defined" in Jest when testing es6 module with RequireJS dependency

查看:489
本文介绍了“未定义".测试带有RequireJS依赖的es6模块时在Jest中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无法运行的Jest测试套件,因为它要测试的组件取决于RequireJS模块.这是我看到的错误:

I have a Jest test suite that fails to run because the component it's trying to test depends on a RequireJS module. Here's the error I'm seeing:

 FAIL  __tests__/components/MyComponent.test.js
  ● Test suite failed to run

    ReferenceError: define is not defined

      at Object.<anonymous> (node_modules/private-npm-module/utils.js:1:90)

该组件具有以下导入:

import utils from 'private-npm-module';

private-npm-module的设置如下:

define('utils', [], function() {
  return {};
});

使用babel对MyComponent进行编译并在浏览器中运行时,依赖项将正确运行.此问题仅影响单元测试.如何让我的测试套件在具有RequireJS依赖项的组件上运行?

When MyComponent is transpiled with babel and run in the browser, the dependency operates correctly. This issue only affects the unit test. How can I get my test suite to run on a component with a RequireJS dependency?

我在package.json的Jest配置中使用babel-jest作为我的scriptPreprocessor.我正在使用jest v0.15.1.

I'm using babel-jest as my scriptPreprocessor in package.json's jest config. I'm using jest v0.15.1.

推荐答案

因此,Jest不支持RequireJS.在我的特定情况下,在MyComponent.test.js顶部模拟我的依赖关系是最简单,最合适的方法:

So, RequireJS is not supported by Jest. In my particular case, it was easiest and most appropriate to mock my dependency at the top of MyComponent.test.js:

jest.mock('private-npm-module', () => {
  // mock implementation
})

import MyComponent from '../../components/MyComponent';

这样,在加载MyComponent时,其依赖关系已经被模拟,因此它不会尝试加载RequireJS模块.

This way, when MyComponent is loaded, its dependency is already mocked, so it won't try to load the RequireJS module.

如果确实需要为测试加载RequireJS模块,则可以使用 jest的transform配置将您的实现包装在RequireJS to ES6转换器中.

If you really do need to load your RequireJS module for your test, it may be possible to use jest's transform configuration to wrap your implementation in a RequireJS to ES6 converter.

这篇关于“未定义".测试带有RequireJS依赖的es6模块时在Jest中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆