演示:https://codesandbox.io/s/mocha-chai-http-tests-o31ov我尝试在测试阶段像这样添加应用程序级中间件
it("GET/ Get custom response", function(done) {
app.use("/custom", (req, res, next) => {
res.status(200).send({
customMessage: "custom",
customData: {
version: "v1"
}
});
});
chai
.request(app)
.get("/custom")
.end((err, res) => {
console.log("CUSTOM", res.body);
res.should.have.status(200);
res.body.should.be.a("object");
res.body.should.have.property("customMessage");
res.body.should.have.property("customData");
done();
});
});
但是测试没有使用它,它从根本上属于404中间件。如何在测试中使用自定义路由?
中间件的加载顺序很重要:首先加载的中间件功能也将首先执行。
[尝试访问/custom
路由的原因404是在404错误处理程序中间件之后加载此路由。我们需要在404错误处理程序中间件之前保持/custom
路由负载。这是一个解决方案:
app.js
:
const createError = require('http-errors');
const express = require('express');
function createApp(customRoute) {
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use('/api', function(req, res) {
res.status(200).send({
message: 'API',
data: {
version: 'v1',
},
});
});
if (customRoute) {
app.use(customRoute.route, customRoute.controller);
}
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
res.status(err.status).send({
status: err.status,
error: err,
});
});
return app;
}
module.exports = createApp;
app.test.js
:
const chai = require('chai');
const chaiHttp = require('chai-http');
const createApp = require('./app');
chai.use(chaiHttp);
chai.should();
describe('API test', function() {
it('GET/ Get root response', function(done) {
const app = createApp();
chai
.request(app)
.get('/api')
.end((err, res) => {
console.log('NORMAL', res.body);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('message');
res.body.should.have.property('data');
done();
});
});
it('GET/ Get custom response', function(done) {
const customRoute = {
route: '/custom',
controller: (req, res, next) => {
res.status(200).send({
customMessage: 'custom',
customData: {
version: 'v1',
},
});
},
};
const app = createApp(customRoute);
chai
.request(app)
.get('/custom')
.end((err, res) => {
console.log('CUSTOM', res.body);
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('customMessage');
res.body.should.have.property('customData');
done();
});
});
});
单元测试结果:
API test
NORMAL { message: 'API', data: { version: 'v1' } }
✓ GET/ Get root response (44ms)
CUSTOM { customMessage: 'custom', customData: { version: 'v1' } }
✓ GET/ Get custom response
2 passing (62ms)