Jest cannot find tests when tests are located under `node_modules` directory

Viewed 37

After I performed refactoring on my project, I found that Jest could not find any test modules. It reported following error.

No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
No files found in /home/.../node_modules/.../... /api.
Make sure Jest's configuration does not exclude this directory.
To set up Jest, make sure a package.json file exists.
Jest Documentation: https://jestjs.io/docs/configuration
Pattern:  - 0 matches

After I examined a while, I found the smallest reproducible example is following :

node_modules/foo.js

function foo() { 
  return 'hello'; 
} 
module.exports.foo = foo;

node_modules/foo.test.js

test( 'foo' , ()=>{ 
  console.error( require('./foo.js' ).foo() ); 
});

And if foo.js and foo.test.js are moved out from node_modules directory, Jest works as normal.


In order to avoid long relative package names, I put all files under node_modules directory. If possible, I don't want to relocate them.

Is there any workaround or, if possible, any permanent proper solution for the issue?


Edited) Why do you want to put those in node_modules ?
See Document src/node_modules as official solution for absolute imports

1 Answers

This is a known bug and the bug was already fixed.

A quick fix is creating jest.config.js in the root directory of your project tree as following :

const config = { 
  "testEnvironment": "node", 
  "testPathIgnorePatterns": [], 
  "haste": { 
    "retainAllFiles": true 
  } 
}; 
module.exports = config;                                                              

Or you can add following in the package.json :

"jest": { 
    "testEnvironment": "node", 
    "testPathIgnorePatterns": [], 
    "haste" : { 
      "retainAllFiles": true 
    } 
} 

This answer is a sort of my reminder; hoping this saves a couple of precious hours of my friends.

Related