How can I use my webpack's html-loader imports in Jest tests?

。_饼干妹妹 提交于 2019-11-30 13:23:31

I encountered this specific problem recently and creating your own transform preprocesser will solve it. This was my set up:

package.json

"jest": {
    "moduleFileExtensions": [
      "js",
      "html"
    ],
    "transform": {
      "^.+\\.js$": "babel-jest",
      "^.+\\.html$": "<rootDir>/test/utils/htmlLoader.js"
    }
 }

NOTE: babel-jest is normally included by default, but if you specify a custom transform preprocessor, you seem to have to include it manually.

test/utils/htmlLoader.js:

const htmlLoader = require('html-loader');

module.exports = {
    process(src, filename, config, options) {
        return htmlLoader(src);
    }
}
Samuel Mburu

A bit late to the party, but wanted to add that there is also this html-loader-jest npm package out there to do this if you wanted to go that route.

Once you npm install it you will add it to your jest configuration with

"transform": {
        "^.+\\.js$": "babel-jest",
        "^.+\\.html?$": "html-loader-jest"
    }

Maybe your own preprocessor file will be the solution:

ScriptPreprocessor

Custom-preprocessors

scriptpreprocessor: The path to a module that provides a synchronous function from pre-processing source files. For example, if you wanted to be able to use a new language feature in your modules or tests that isn't yet supported by node (like, for example, ES6 classes), you might plug in one of many transpilers that compile ES6 to ES5 here.

I created my own preprocessor when I had a problems with my tests after added transform-decorators-legacy to my webpack module loaders.

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