You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mocha为JavaScript为主的NPM包运行Typescript单元测试并导入JS模块

问题解决步骤

前置操作:安装必要依赖

首先确保你已经安装了所有需要的开发依赖,执行以下命令:

npm install -D typescript ts-node @types/mocha @types/node assert

问题1:直接运行mocha提示No test files found

原因

新版Mocha已经废弃了mocha.opts配置文件,你写的配置不会被加载,Mocha默认只识别.js后缀的测试文件,所以找不到.ts文件。

解决方法

二选一即可:

  • 方案1:使用新版Mocha配置文件
    在项目根目录新建.mocharc.json,替换原来的mocha.opts,内容如下:
{
  "require": "ts-node/register",
  "recursive": true,
  "reporter": "spec",
  "ui": "bdd",
  "timeout": 20000,
  "spec": "test/**/*.ts"
}

配置完成后直接运行npx mocha即可正常识别.ts测试文件。

  • 方案2:修改启动命令
    在package.json的scripts字段中添加测试命令:
{
  "scripts": {
    "test": "mocha -r ts-node/register test/**/*.ts"
  }
}

后续运行npm test执行测试即可。


问题2:导入../srcJS包报错找不到模块

原因

TypeScript默认不识别JS模块的导入,也没有匹配的类型声明文件,所以会抛出找不到模块的错误。

解决方法

在项目根目录新建tsconfig.json,添加以下配置:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "allowJs": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "resolveJsonModule": true
  },
  "include": ["test/**/*", "src/**/*"]
}

核心配置说明:

  • allowJs: true 允许TypeScript识别导入JS文件
  • esModuleInterop: true 兼容ES模块导入CommonJS导出的语法,适配你用import导入JS包的写法
  • include 字段把src和test目录都加入TypeScript的解析范围
    如果配置完成后还是导入失败,可以把导入语句改成import * as MyPackage from '../src'试试。

额外注意事项

你当前的test.ts里没有导入assert模块,测试运行时会抛出assert is not defined错误,需要在test.ts顶部添加导入语句:

import * as assert from 'assert'

内容的提问来源于stack exchange,提问作者Cerin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 10:15:03