在浏览器中使用Typescript运行Mocha时如何让测试函数全局可用
解决方法
报错核心原因
- ES 模块的静态
import存在提升特性,你写在M.setup('bdd')之后的测试文件导入语句,实际执行顺序会早于M.setup执行,此时 Mocha 还未完成测试接口的挂载 - Mocha 的 ES2018 模块版本默认不会主动把
describe/it/before等测试接口暴露到浏览器全局作用域
具体实现步骤
1. 修改入口 test.ts 逻辑
调整初始化顺序,先完成 Mocha 全局挂载,再动态导入测试文件,最后执行测试:
// test.ts import 'mocha/mocha.css'; import * as M from 'mocha/mocha-es2018'; import { expect } from 'chai'; // 可选:把 chai 的 expect 也挂载到全局,测试文件不用重复导入 (window as any).expect = expect; // 初始化 Mocha,配置开启全局暴露 M.setup({ ui: 'bdd', global: true }); // 兼容兜底:手动把 BDD 测试接口挂载到全局 window const bddInterface = (M as any).interfaces.bdd; Object.assign(window, bddInterface()); // 必须使用动态导入,保证所有测试文件在 Mocha 初始化完成后才加载 const runAllTests = async () => { // 导入所有测试文件 await import('./unit/sum.spec.ts'); // 可继续添加更多测试文件导入 // await import('./unit/other.spec.ts'); // 所有测试加载完成后执行 M.run(); }; runAllTests();
2. 添加 TypeScript 全局类型声明(可选,TS 项目需要)
在测试目录下新建 test.d.ts 类型声明文件,避免 TS 报错找不到全局测试函数:
// test.d.ts declare global { const describe: typeof import('mocha').describe; const it: typeof import('mocha').it; const before: typeof import('mocha').before; const after: typeof import('mocha').after; const beforeEach: typeof import('mocha').beforeEach; const afterEach: typeof import('mocha').afterEach; const expect: typeof import('chai').expect; } export {}
注意事项
- 不要使用静态
import导入测试文件,静态导入的执行优先级远高于普通代码,一定会跑到 Mocha 初始化之前触发报错 - 配置完成后所有外部测试文件都可以直接使用
describe/it等全局函数,不需要额外导入 Mocha 相关依赖
内容的提问来源于stack exchange,提问作者philipp
相关产品推荐
相关产品推荐

