Jest测试时node_modules模块导入报undefined,求排查配置问题
为何Jest无法解析node_modules模块,导入后返回undefined?
问题重现
执行Jest测试时,所有从node_modules导入的模块均返回undefined,示例测试代码如下:
import lodash from 'lodash' it('test', () => { expect(lodash.max([1,2])).toBe(2) })
测试抛出错误:
Cannot read properties of undefined (reading 'max') TypeError: Cannot read properties of undefined (reading 'max')
相关配置文件:
jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */ const tsconfig = require('./tsconfig.json') const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig) module.exports = { preset: 'ts-jest', testEnvironment: 'node', moduleNameMapper, }
webpack.config.js
const path = require('path') const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin').default const nodeExternals = require('webpack-node-externals') module.exports = { entry: './src/server.ts', target: 'node', externals: [nodeExternals()], devtool: 'source-map', mode: process.env.RUNTIME_ENV === 'production' ? 'production' : 'development', module: { rules: [ { test: /\.(ts|js)$/, use: 'ts-loader', exclude: /node_modules/, }, { test: /\.(graphql|gql)$/, loader: '@graphql-tools/webpack-loader', }, ], }, resolve: { extensions: ['.tsx', '.ts', '.js'], plugins: [new TsconfigPathsPlugin({})], }, output: { filename: '[name].js', path: path.resolve(__dirname, 'dist'), }, }
tsconfig.json
{ "compilerOptions": { "lib": ["ESNext"], "moduleResolution": "node", "noUnusedLocals": true, "noUnusedParameters": true, "removeComments": true, "sourceMap": true, "target": "ES2020", "outDir": "lib", "isolatedModules": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "resolveJsonModule": true, "baseUrl": ".", "allowJs": true, "allowSyntheticDefaultImports": true }, "include": ["src/**/*.ts","./global.d.ts"], "exclude": [ "node_modules/**/*", "_warmup/**/*", ".vscode/**/*" ] }
问题原因
核心问题是tsconfig-paths-jest生成的moduleNameMapper完全覆盖了Jest默认的模块解析规则,导致Jest无法正确识别并加载node_modules中的第三方模块。
解决办法
1. 修复jest.config.js的moduleNameMapper配置
不要直接将tsconfig-paths-jest的返回值赋值给moduleNameMapper,而是将其合并到Jest的默认配置中,保留Jest对node_modules的解析逻辑:
/** @type {import('ts-jest').JestConfigWithTsJest} */ const tsconfig = require('./tsconfig.json') const pathsMapper = require('tsconfig-paths-jest')(tsconfig) module.exports = { preset: 'ts-jest', testEnvironment: 'node', // 合并路径别名映射,保留Jest默认模块解析规则 moduleNameMapper: { ...pathsMapper, }, }
2. 验证依赖完整性
确保已安装必要的开发依赖:
npm install --save-dev ts-jest typescript @types/jest @types/lodash
3. 重新运行测试
修改配置后,重新执行Jest测试,此时应该能正确解析lodash等第三方模块,测试正常运行。
内容的提问来源于stack exchange,提问作者zibra
相关产品推荐
相关产品推荐

