IowA
IowA

Reputation: 1056

React component testing with Jest

I want to test my components using jest, but when I run it i am getting `Cannot find module 'react-router/Router' from 'Router.js'

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:191:17)
  at Object.<anonymous> (node_modules/react-router-dom/Router.js:5:15)`

if I start development server my application is working corectly.

My jest config in package.json looks like:

 "jest": {
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "moduleDirectories": [
      "<rootDir>/node_modules",
      "<rootDir>/src"
    ]
  }

Upvotes: 1

Views: 582

Answers (1)

Michael Jungo
Michael Jungo

Reputation: 32972

You are overwriting moduleDirectories and you don't include the default, which is ["node_modules"]. You are including <rootDir>/node_modules instead, which is not the same, because that will only look into the node_modules in the root of your project, whereas "node_modules" follows the module resolution of Node.js. The behaviour of Node.js is to look for node_modules in the current directory, if the module is not found it looks in its parent directory (../node_modules) and so on until the module was found or the root of your file system is reached. For more details see Loading from node_modules Folders.

The important difference is that nested modules break if you change the default behaviour. In your case react-router-dom uses react-router as a dependency, and the node_modules might look like this:

node_modules
├─ jest
└─ react-router-dom
    └─ node_modules
        └─ react-router

In this example, node_modules in the root directory only contains jest and react-router-dom, so it wouldn't find react-router.

Note: npm started hoisting dependencies with version 3 and the result would look like this:

node_modules
├─ jest
├─ react-router-dom
└─ react-router

See also npm v3 Dependency Resolution.

If you are indeed using a severely outdated npm version, you should upgrade immediately. But you should never rely on that behaviour, and always include the default module resolution.

"jest": {
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "moduleDirectories": [
    "node_modules",
    "<rootDir>/src"
  ]
}

Upvotes: 3

Related Questions