“Define is not defined” in Jest when testing es6 module with RequireJS dependency

爱⌒轻易说出口 提交于 2019-12-09 14:44:08

问题


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)

The component has the following import:

import utils from 'private-npm-module';

And the private-npm-module is set up like so:

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

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?

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


回答1:


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';

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

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.



来源:https://stackoverflow.com/questions/40919028/define-is-not-defined-in-jest-when-testing-es6-module-with-requirejs-dependenc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!