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

Mocha + Chai 测试 NodeJS 接口时预期失败却始终通过如何解决

问题原因

  • Mocha默认不会等待异步逻辑执行完成就会结束测试用例。你当前代码中的requester.get返回Promise对象属于异步任务,你没有告知Mocha需要等待该任务完成再判定用例结果,所以测试用例在接口请求还未返回时就已经判定为通过,运行结果中测试通过提示后才打印200状态码就是该问题的直接表现。

修复方案

以下三种方案任选其一即可:

方案1:返回Promise

在it块内将请求的Promise对象return出去,Mocha会自动等待Promise执行完成后再判定测试结果:

it("should return all users and 400", function(){
    return requester.get("/api/users")
    .then(function(res){
        console.log(res.status);
        expect(res).to.have.status(400);
    })
    .catch(function(err){
        throw(err);
    })
})

方案2:使用async/await语法(可读性更高)

将it的回调函数声明为async,内部await异步请求的结果:

it("should return all users and 400", async function(){
    const res = await requester.get("/api/users")
    console.log(res.status);
    expect(res).to.have.status(400);
})

方案3:使用done回调

通过Mocha提供的done参数手动告知测试结束,错误场景需将错误传入done:

it("should return all users and 400", function(done){
    requester.get("/api/users")
    .then(function(res){
        console.log(res.status);
        expect(res).to.have.status(400);
        done();
    })
    .catch(function(err){
        done(err);
    })
})

修复后重新运行测试,就会正确触发断言失败的提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:24:03