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

后端 未结 3 556
一生所求
一生所求 2020-12-16 01:18

I am just getting started with the Jest test framework and while straight up unit tests work fine, I am having massive issues testing any component that in its module (ES mo

相关标签:
3条回答
  • 2020-12-16 01:59

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-16 02:21

    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"
        }
    
    0 讨论(0)
  • 2020-12-16 02:21

    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.

    0 讨论(0)
提交回复
热议问题