webpack require non-js content in jest unit-tests

白昼怎懂夜的黑 提交于 2019-12-23 12:08:03

问题


Recently I've converted one of my projects to webpack & babel. It is made out of knockout components.

I'm running into a problem while running the unit-tests. If I have a file in the tests folder like

import component from '../custom-options';

test('adds 1 + 2 to equal 3', () => {
  expect(3).toBe(3);
});

The problem is that the component is a module which has a require of the sort

var htmlString = require('./custom-options.html');

When I try to run the website itself it runs fine, as the raw loader is configured for this require. However, when I run jest the test outputs:

 custom-options.html:1
 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){?<div id="custom-options-containe" class="mod--custom-options">
                                                                                          ^
SyntaxError: Unexpected token <

  at transformAndBuildScript (node_modules\jest-cli\node_modules\jest-runtime\build\transform.js:284:10)
  at custom-options.js:13:38
  at Object.<anonymous> (custom-options.js:93:3)

Any idea why this is happening? I thought jest was at fault but I've tried subbing it out with Ava and the result is the same. I'm beginning to think it's a babel problem.

I'm running jest with the babel-jest preprocessor.


回答1:


You can create a global mock for all none JS files in you jest settings in the package.json like this:

"jest": {
  "moduleNameMapper": {
    "^.+\\.html$": "<rootDir>/__mocks__/htmlMock.js"
  }
}

then create the file htmlMock.js in the __mocks__ folder in your project root with the following content:

module.exports = 'test-file-stub';

For more info have a look here

If you want do have a special mock for every test case you can also mock the file in your test like this:

jest.mock('path/from/test/to/custom-options.html', ()=> 'test-file-stub');

Notice that the path is relative to the test file not to the file you want to test.



来源:https://stackoverflow.com/questions/40302246/webpack-require-non-js-content-in-jest-unit-tests

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