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
相关产品推荐
相关产品推荐

