webpack require non-js content in jest unit-tests
babel-jest, babeljs, jestjs, webpack
Solution
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.
Problem
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.