0

I'm updating an older Webpack2 project to Webpack4 and switching the tests over to Jest but have a seemingly simple problem with a couple of the webpack related bits.

Specifically, the project structure for the troublesome bits look like this:

src
    - constants
        - index.js
    - config
        - base.js
        - test.js
        - dev.js
        - dist.js

During testing, the classes under test use import config from 'config' so issue number one is allowing them to find the right config file. With Webpack2 this is subbed in by webpack itself, but obviously not during Jest tests.

I can resolve this by hard coding the specific test config into the moduleNameMapper in the jest config in package.json like so:

"jest": {
    "moduleNameMapper": {
        "^config$": "<rootDir>/src/config/test.js"
    }
}

This appears to work.

The second part of my issue is allowing Jest to find named exports src/constants/index.js using syntax like import { SOME_CONST } from 'constants'.

When I try to use moduleNameMapper I get back undefined from anything that uses the constants and I believe this is because moduleNameMapper is largely used to mock out dependencies rather than supply them. With this in mind I think I need to use modulePaths or moduleDirectories to allow the constants to be located.

I've tried the following configurations (not simultaneously) without any luck:

"modulePaths": [
  "<rootDir>/src/constants",
  "src/constants"
],
"moduleDirectories": [
  "node_modules",
  "src",
  "src/constants",
  "/src/constants"
  "/src/constants/",
  "./src/constants"
],

What should the correct config be for Jest to locate my constants?

If it's any help I'm trying to mimic this Webpack2 config in Jest

  resolve: {
    alias: {
      constants: `${this.srcPathAbsolute}/constants/`
    }
  }
skyboyer
  • 22,209
  • 7
  • 57
  • 64
dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89
  • Hey I am facing similar issue...did u find any solution? – Rujoota Shah Mar 22 '19 at 21:13
  • 1
    @RujootaShah In the end I had to change my alias to `appconstants` and it worked, I'm guessing `constants` is reserved in some way – dougajmcdonald Mar 25 '19 at 08:26
  • I am not using constants or anything of that kind....I am just using simple stuff like 'xyz'....but still facing the issue....whats the version of webpack and jest you are using? – Rujoota Shah Mar 26 '19 at 17:15
  • I'm afraid I'm not sure quite what you mean here, could you post you own question and link to this question and me in the comments with an example of your config. – dougajmcdonald Mar 27 '19 at 07:51
  • Sure....here it is... https://stackoverflow.com/questions/55266375/react-test-with-jest-does-not-honor-modulenamemapper-from-webpack-aliases – Rujoota Shah Mar 28 '19 at 17:51

0 Answers0