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

Express接口supertest测试报AssertionError: expected undefined to equal 200排查

问题定位与修复方案

你遇到的AssertionError: expected undefined to equal 200错误由两部分代码问题共同导致,具体修复如下:

1. 业务代码(app.js)问题

  • 定义的路由未挂载到Express实例,/postp接口实际不存在
  • PORT变量未提前声明,启动服务时会直接抛错
  • 路由处理仅设置了状态码,没有主动结束响应,请求会一直挂起

修复后代码:

const express = require("express");
const app = express();
const router = express.Router();
// 声明端口变量
const PORT = 3000;

router.get('/postp',(req,res)=>{
  // 设置状态码后结束响应
  res.status(200).end();
})
// 挂载路由到app实例
app.use(router);

app.listen(PORT, () => {
  console.log(`Connected to PORT : ${PORT}`);
});
module.exports = app;

2. 测试用例问题

supertest发起的请求是异步操作,你当前同步读取response.status时,请求还未返回,response还未生成,所以status为undefined。需要用异步写法等待请求返回后再做断言。

修复后代码(推荐用async/await写法更简洁):

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

describe('Blog',function(){
  // 用async标记异步测试
  it('get blogs', async function(){
    const response =  await request(app).get('/postp');
    expect(response.status).to.be.equal(200);
  })
})

如果要用回调写法也可以参考:

it('get blogs', function(done){
  request(app).get('/postp')
    .end((err, response) => {
      expect(response.status).to.be.equal(200);
      done();
    })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:54:07