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

使用Supertest与Mocha时断言失败但测试仍显示通过的问题

问题:Supertest+Mocha断言失败但测试显示通过

我在使用Supertest和Mocha进行接口测试时遇到异常:当expect断言失败时,控制台输出了AssertionError,但测试结果却显示“1 passing”,未正确标记为失败。

报错信息

Create Tenant Account
    Login to a user who is Admin
POST /api/auth/sign_in 200 745.330 ms - 3341
AssertionError: expected { isAdmin: true, …(4) } to have own property 'isAdm21221in'
    at file:///C:/Users/rambo/Desktop/psm-solution/backend/test/createTenant.test.js:34:28
    at processTicksAndRejections (node:internal/process/task_queues:95:5) {
  actual: {
    isAdmin: true,
    isTenantAdmin: true,
    provider: 'email',
    providers: [ 'email' ],
    tenantId: 'f997ca0e-9bed-4550-a115-1175ff1406e7'
  },
  expected: undefined,
  showDiff: false
}
      ✔ should login to a user and recieve a 200 http status code (970ms)


  1 passing (994ms)

测试代码

import supertest from 'supertest';
import { app, supabase } from '../src/server.ts';
import { expect } from 'chai';

describe('Create Tenant Account', () => {

  describe('Login to a user who is Admin', () => {
    it('should login to a user and recieve a 200 http status code', done => {
      supertest(app)
      .post('/api/auth/sign_in')
      .send({email: 'testmest@evt2.de', password: '123456'})
      .then(res => {

        expect(appmeta).to.haveOwnProperty('isAdm21221in');
        expect(res.statusCode).to.equal(200);
      
        done();
      })
      .catch(e => {
        console.log(e);
        done();
      });
    });
  });

});

错误原因及解决方法

核心问题:Mocha未捕获到断言错误

你的catch块里调用done()时没有传入错误对象,Mocha无法感知到测试过程中发生了异常,因此会默认标记测试为通过。另外代码里的appmeta变量未定义,这也是导致断言失败的直接原因,需要先从响应中获取对应的数据(比如res.body.appmeta,具体字段根据实际接口返回结构调整)。

解决方式1:修复catch块的done调用

修改catch部分,把错误传给done():

.catch(e => {
  console.log(e);
  done(e); // 传入错误,Mocha会标记测试失败
});

解决方式2:改用async/await写法(更推荐)

避免callback嵌套的问题,代码更直观:

it('should login to a user and recieve a 200 http status code', async () => {
  const res = await supertest(app)
    .post('/api/auth/sign_in')
    .send({email: 'testmest@evt2.de', password: '123456'});
  
  // 先修正appmeta的来源,比如假设是res.body里的字段
  const appmeta = res.body.appmeta; 
  expect(appmeta).to.haveOwnProperty('isAdmin'); // 修正拼写错误的字段名
  expect(res.statusCode).to.equal(200);
});

额外提示

你断言里的字段名isAdm21221in是拼写错误,应该是isAdmin,这也是导致断言失败的原因之一,记得修正。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:25:23