使用Jest测试TypeScript函数时出现Cannot find module 'import-local'错误
Jest + TypeScript 测试报错:Cannot find module 'import-local'
要在VSCode中使用Jest测试TypeScript函数,跟着Jest官方快速入门指南安装了相关依赖,但在终端运行jest命令后出现以下错误:
node:internal/modules/cjs/loader:1147 throw err; ^ Error: Cannot find module 'import-local' Require stack: - /usr/share/nodejs/jest/bin/jest.js at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15) at Module._load (node:internal/modules/cjs/loader:985:27) at Module.require (node:internal/modules/cjs/loader:1235:19) at require (node:internal/modules/helpers:176:18) at Object.<anonymous> (/usr/share/nodejs/jest/bin/jest.js:9:21) at Module._compile (node:internal/modules/cjs/loader:1376:14) at Module._extensions..js (node:internal/modules/cjs/loader:1435:10) at Module.load (node:internal/modules/cjs/loader:1207:32) at Module._load (node:internal/modules/cjs/loader:1023:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) { code: 'MODULE_NOT_FOUND', requireStack: [ '/usr/share/nodejs/jest/bin/jest.js' ] } Node.js v20.11.1
当前项目的package.json内容:
{ "devDependencies": { "@types/jest": "^29.5.12", "import-local": "^3.1.0", "jest": "^29.7.0", "ts-jest": "^29.1.2" }, "scripts": { "test": "jest" } }
解决方法
- 使用npm脚本执行测试:直接运行
npm run test,这个命令会调用项目本地安装的Jest,能正确识别node_modules里的import-local依赖,避免全局Jest的环境问题。 - 用npx调用本地Jest:如果习惯直接敲
jest命令,换成npx jest,npx会自动找到项目本地的Jest可执行文件。 - 重新安装依赖:如果
node_modules存在损坏,删除node_modules文件夹和package-lock.json文件,然后运行npm install重新安装所有依赖。
内容的提问来源于stack exchange,提问作者Nondikass
相关产品推荐
相关产品推荐

