You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest无法识别node_modules目录下的测试文件问题求助

Jest无法识别node_modules内测试文件的解决办法

问题描述

重构项目后,Jest无法找到任何测试模块,报错如下:

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

最小复现示例:
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() ); 
});

将上述文件移出node_modules目录后,Jest即可正常运行。

将文件放在node_modules的原因是参考了Create React App的官方方案——通过src/node_modules实现绝对导入,避免使用冗长的相对路径。

临时解决办法

方法1:修改Jest配置文件指定测试路径

在jest.config.js中添加或修改testMatch配置,明确包含node_modules内的测试文件:

module.exports = {
  testMatch: [
    '**/__tests__/**/*.[jt]s?(x)',
    '**/?(*.)+(spec|test).[tj]s?(x)',
    '**/node_modules/**/*.test.js' // 新增规则匹配node_modules内的测试文件
  ]
};

方法2:启动Jest时添加命令行参数

直接在启动命令中指定测试文件的匹配规则:

jest --testMatch="**/node_modules/**/*.test.js"

方法3:移除目标目录的转译忽略

如果测试文件需要转译,可在jest.config.js中修改transformIgnorePatterns,排除特定子目录(比如示例中的foo):

module.exports = {
  transformIgnorePatterns: ['/node_modules/(?!foo)/']
};

永久合理方案

方案1:用Jest的moduleNameMapper实现绝对导入(推荐)

无需将文件放入node_modules,直接通过配置映射绝对路径:
在jest.config.js中添加:

module.exports = {
  moduleNameMapper: {
    '^foo$': '<rootDir>/src/foo.js' // 将`require('foo')`映射到实际文件路径
  }
};

代码中可直接用require('foo')实现绝对导入,测试文件放在常规目录(如src/__tests__/foo.test.js)即可被Jest正常识别。

方案2:分离测试文件与源文件

保持node_modules内的源文件用于绝对导入,将测试文件移出node_modules,放在对应目录(如src/__tests__/foo.test.js),测试时直接通过绝对路径引入源文件:

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

方案3:配置Jest的测试根目录

在jest.config.js中设置roots或testPaths,包含node_modules内的目标目录:

module.exports = {
  roots: ['<rootDir>/node_modules/foo'] // 指定测试根目录为node_modules内的foo文件夹
};

内容的提问来源于stack exchange,提问作者Musique Non Stop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:24:28