在Chai+Mocha单元测试中如何访问req对象?
解决Chai/Mocha测试中无法访问req对象的问题
核心问题
你在测试回调里直接使用req变量,但这个变量并未定义——chai.request的end回调参数只有err和res,请求对象需要从res.req中获取。如果之前尝试res.req无效,大概率是中间件执行逻辑或测试时机的问题。
修复方案
1. 正确获取req对象
把测试代码里的expect(req)改成expect(res.req),chai-http会将请求对象挂载在响应对象的req属性上。
2. 检查中间件执行逻辑
如果还是拿不到id,请排查以下两点:
- 确认添加
id的中间件确实挂载到了/这个POST路由的处理链中 - 检查是否在发送响应(比如
res.send())之后才给req添加id,这种情况下res.req里不会有该属性,因为响应发送后请求流程已结束
修改后的测试代码
//Imports necessary modules const chai = require('chai'); const chaiHttp = require('chai-http'); const expect = chai.expect; const {mockData} = require('./mock-data.js') const app = require('../app.js'); chai.use(chaiHttp); describe('/process POST', () => { it('it should calculate the points value and add it to the req object', (done) => { chai.request(app).post('/').send(mockData).end((err, res) => { // 从res.req获取请求对象 expect(res.req).to.have.property('id'); done(); }); }); });
额外排查建议
- 如果使用Promise风格(
.then()),同样要从响应对象中获取req:it('should add id to req object', () => { return chai.request(app).post('/').send(mockData) .then(res => { expect(res.req).to.have.property('id'); }); }); - 确保中间件在路由处理前执行且调用了
next():// 示例中间件,需放在路由定义前 app.use((req, res, next) => { req.id = 'target-id'; next(); // 必须调用next()让请求继续流转 }); app.post('/', (req, res) => { res.send({ success: true }); });
内容的提问来源于stack exchange,提问作者Brenden
相关产品推荐
相关产品推荐

