How to use jest with webpack?

前端 未结 12 2586
抹茶落季
抹茶落季 2020-12-08 06:00

I use webpack to develop a React component. Here is a simple version of it:

\'use strict\';

require(\'./MyComponent.less\');

var React = require(\'react\')         


        
12条回答
  •  暖寄归人
    2020-12-08 06:48

    The cleanest solution I found for ignoring a required module is to use the moduleNameMapper config (works on the latest version 0.9.2)

    The documentation is hard to follow. I hope the following will help.

    Add moduleNameMapper key to your packages.json config. The key for an item should be a regex of the required string. Example with '.less' files:

    "moduleNameMapper": { "^.*[.](less|LESS)$": "EmptyModule" },
    

    Add a EmptyModule.js to your root folder:

    /**
     * @providesModule EmptyModule
     */
    module.exports = '';
    

    The comment is important since the moduleNameMapper use EmptyModule as alias to this module (read more about providesModule).

    Now each require reference that matches the regex will be replaced with an empty string.

    If you use the moduleFileExtensions configuration with a 'js' file, then make sure you also add the EmptyModule to your 'unmockedModulePathPatterns'.

    Here is the jest configuration I ended up with:

    "jest": {
      "scriptPreprocessor": "/node_modules/babel-jest",
      "moduleFileExtensions": ["js", "json","jsx" ],
      "moduleNameMapper": {
        "^.*[.](jpg|JPG|gif|GIF|png|PNG|less|LESS|css|CSS)$": "EmptyModule"
      },
      "preprocessorIgnorePatterns": [ "/node_modules/" ],
      "unmockedModulePathPatterns": [
        "/node_modules/react",
        "/node_modules/react-dom",
        "/node_modules/react-addons-test-utils",
        "/EmptyModule.js"
      ]
    }
    

提交回复
热议问题