使用Mocha进行TypeScript单元测试时遭遇「Cannot use import statement outside a module」错误
解决Mocha + TypeScript 中 "Cannot use import statement outside a module" 错误
问题根源
你的项目存在两个核心冲突:
package.json中设置了"type": "module"(启用ES模块),但tsconfig.json里compilerOptions.module配置为commonjs(编译为CommonJS模块),模块系统不统一。- Mocha 没有被配置为使用
ts-node处理 TypeScript 文件,导致直接尝试解析TS文件中的ES语法,引发报错。
解决方案步骤
1. 统一模块系统
首先移除 package.json 中的 "type": "module" 字段,因为你的TypeScript配置是编译为CommonJS,保持配置一致:
{ "name": "unittest", "version": "1.0.0", "description": "", "main": "index.js", // 移除这一行:"type": "module", "scripts": { "test": "mocha", "build": "rm -rf dist && tsc" }, // ... 其他配置不变 }
2. 配置Mocha使用ts-node处理TypeScript
修改 package.json 中的 mocha 配置,指定用 ts-node/register 来转译TypeScript文件,同时调整测试文件匹配规则(只加载.spec.ts测试文件,避免误加载源文件):
{ // ... 其他配置 "mocha": { "check-leaks": true, "globals": ["crypto"], "recursive": true, "require": ["ts-node/register"], // 新增该行,让Mocha用ts-node处理TS文件 "spec": ["./*.spec.ts"] // 仅匹配测试文件 } }
你也可以直接修改scripts.test命令,显式指定ts-node:
"scripts": { "test": "mocha -r ts-node/register ./*.spec.ts", "build": "rm -rf dist && tsc" }
3. 验证修复
运行 npm test,此时Mocha会通过ts-node正确转译TypeScript测试文件,执行你的测试用例。
额外检查点
- 确认
ts-node和typescript已正确安装(你的devDependencies中已包含,无需额外安装)。 - 如果后续需要切换为ES模块,需调整
tsconfig.json的module为ESNext,同时Mocha命令需要添加--experimental-specifier-resolution=node参数,并且保留package.json的"type": "module",但这种配置复杂度较高,入门阶段推荐先使用CommonJS保持简单。
内容的提问来源于stack exchange,提问作者PlayHardGoPro
相关产品推荐
相关产品推荐

