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

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

问题描述

我有一个 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 {};
});

MyComponent 用 babel 转译并在浏览器中运行时,依赖项运行正常.此问题仅影响单元测试.如何让我的测试套件在具有 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 到 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.

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

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