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

Mocha测试显示通过但assert/expect断言失败未触发测试用例失败

根因分析

你代码中的try...catch块捕获了断言失败抛出的异常,仅在控制台打印错误而没有向上抛出,Mocha框架无法接收到测试失败的信号,因此会判定该用例执行通过。

修复方案

方案1(推荐):移除多余的try...catch

Mocha原生支持async/await语法的异步测试,断言抛出的异常会被Mocha自动捕获并判定用例失败,无需手动捕获异常:

const assert = require('assert');
const expect = require('chai').expect;
const request = require('supertest');
const server = require('../server');

describe('Unit testing the /api/auth/signup route', function () {
  it('Should return OK status', async () => {
    const res = await request(server).post('/api/auth/signup').send({
      email: 'tom@email.com',
      password: 'tompassword',
    });
    // assert和expect断言均可正常生效
    expect(res.body.data.user.email).to.equal('josh@email.com');
    // assert.equal(res.body.data.user.email, 'josh@email.com');
  });
});

方案2:保留try...catch时手动抛出异常

如果确实需要在异常时做自定义处理,需要在catch分支中重新抛出异常,让Mocha可以识别到测试失败:

it('Should return OK status', async () => {
  try {
    let res = await request(server).post('/api/auth/signup').send({
      email: 'tom@email.com',
      password: 'tompassword',
    });
    expect(res.body.data.user.email).to.equal('josh@email.com');
  } catch (err) {
    console.log(err);
    // 抛出异常触发Mocha的失败判定
    throw err;
  }
});

内容的提问来源于stack exchange,提问作者The silent one

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:45:04