使用Jest+Got+TypeScript编写API测试遇模块报错求助
Jest + Got + TypeScript 模块兼容问题解决方案
问题根源
你添加"type": "module"到package.json的操作本身是正确的——这个设置是为了让Node.js将.js/.ts文件当作ES模块处理,适配Got的ES模块语法(import { got } from "got")。但Jest默认基于CommonJS模块系统运行,两者的模块规则冲突,才引发了ReferenceError: module is not defined的报错。
解决步骤
1. 调整Jest配置文件
由于package.json已设为ES模块,Jest的配置文件需要用.cjs后缀(明确标识为CommonJS模块)。新建jest.config.cjs文件,内容如下:
module.exports = { preset: 'ts-jest/presets/default-esm', testEnvironment: 'node', moduleFileExtensions: ['ts', 'js'], transform: { '^.+\\.tsx?$': ['ts-jest', { useESM: true }] }, extensionsToTreatAsEsm: ['.ts'] };
2. 更新package.json的测试脚本
修改scripts中的测试命令,指定Jest使用上述配置文件:
{ "type": "module", "scripts": { "test": "jest --config jest.config.cjs" }, // 其他依赖项... }
3. 配置TypeScript编译选项
确保tsconfig.json的模块配置与ES模块兼容:
{ "compilerOptions": { "target": "ES2020", "module": "Node16", "moduleResolution": "Node16", "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["*.test.ts"] }
4. 确认依赖安装
确保已安装必要的开发依赖:
npm install --save-dev jest ts-jest @types/jest typescript
验证测试
重新运行测试命令npm test,此时Jest会正确处理ES模块语法,Got的请求也能正常执行。
内容的提问来源于stack exchange,提问作者Huckleberry Carignan
相关产品推荐
相关产品推荐

