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

使用Mocha运行ES6模块的Chai测试时出现导出错误的原因

问题原因及解决方案

错误原因

你使用的chai@5.1.1版本移除了默认导出,而测试代码里尝试通过import chai from "chai"这种默认导入方式获取Chai对象,这就触发了SyntaxError: The requested module 'chai' does not provide an export named 'default'错误。

Chai 5.x版本调整了ESM导出规范,不再提供default导出项,所有API都需要通过命名导入或命名空间导入的方式获取。

修复方法

修改测试文件的导入语句,将默认导入改为命名空间导入:

// 替换原导入行
import * as chai from "chai";
import { expect } from "chai";
import chaiHttp from "chai-http";
import app from "../app.js";

chai.use(chaiHttp);

// 后续测试代码保持不变
describe('Version API', () => {
    it('should return the correct version', async () => {
        try {
            const res = await chai.request(app).get('/api/version');
            
            expect(res).to.have.status(200);
        } catch (error) {
            throw new Error(error);
        }
    });
});

也可以合并导入逻辑,写法更简洁:

import * as chai from "chai";
import chaiHttp from "chai-http";
import app from "../app.js";

const { expect } = chai;
chai.use(chaiHttp);

// 测试代码不变

修改完成后,重新运行mocha ./src/tests/**/*.tests.js命令即可正常执行测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 22:40:02