"Undefined" in Jest when testing es6 module with RequireJS

I have a Jest test suite that does not start, because the component that it is trying to test depends on the RequireJS module. Here is the error I see:

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 imports:

 import utils from 'private-npm-module'; 

And private-npm-module configured like this:

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

When MyComponent is passed through a buffer and launched in a browser, the dependency works correctly. This problem only affects the unit test. How can I get my test suite to work with a component with a RequireJS dependency?

I am using babel-jest as my scriptPreprocessor in the package.json jest configuration. I am using jest v0.15.1.

+5
source share
1 answer

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

 jest.mock('private-npm-module', () => { // mock implementation }) import MyComponent from '../../components/MyComponent'; 

Thus, when MyComponent loads, its dependency is already mocking, so it will not try to load the RequireJS module.

If you really need to load your RequireJS module for your test, it may be possible to use the jest transform configuration to port your implementation in the RequireJS converter to ES6.

+4
source

Source: https://habr.com/ru/post/1260666/


All Articles