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

Chai断言本该失败却通过,请求排查测试代码问题

问题原因与解决方案

问题根源

你的测试未按预期失败,核心原因是空的catch块吞掉了断言失败抛出的错误。当assert.strictEqual(data.length, 2)不成立时,Chai会抛出AssertionError,但这个错误被try/catch捕获后没有任何处理,测试框架无法感知到断言失败,因此判定测试通过。

解决方法

方法1:移除不必要的try/catch

异步测试中,测试框架(如Mocha)会自动捕获async函数抛出的异常,无需手动包裹try/catch。修改后代码:

it('trying to get subscriptions with token', async () => {
    const { data } = await axios.get('/subscriptions', config);
    console.log(data); // 返回对象数组
    console.log(data.length); // 长度为3
    assert.strictEqual(data.length, 2);
});

方法2:保留try/catch但重新抛出错误

如果确实需要捕获特定错误(比如请求失败的网络错误),记得在catch中重新抛出断言错误,让测试框架识别失败:

it('trying to get subscriptions with token', async () => {
    try {
        const { data } = await axios.get('/subscriptions', config);
        console.log(data);
        console.log(data.length);
        assert.strictEqual(data.length, 2);
    } catch (error) {
        // 重新抛出错误,测试框架会标记测试失败
        throw error;
    }
});

方法3:使用expect断言(更贴合TDD风格)

如果你想尝试expect,可以用更符合自然语言的写法,同样无需额外try/catch:

it('trying to get subscriptions with token', async () => {
    const { data } = await axios.get('/subscriptions', config);
    expect(data).to.have.lengthOf(2);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:52:27