在Supertest中运行时,此中间件不显示:
app.use((err, req, res, next) => {
// WHY DOES Supertest NOT SHOW THIS ERROR??
console.log("error: ", err.message);
res.status(422).send({ error: err.message });
});
我只是花了大量愚蠢的时间试图找出这个错误:
Driver.findByIdAndDelete(driverId) // Remove NOT Delete
.then(driver => {
res.status(204).send(driver)
})
...
中间件在使用Postman时正确地将错误显示为对正文的响应,但在运行测试时不会。
我打开了两个终端窗口,运行npm run:test
和start
,在运行Postman之前没有显示任何有帮助的内容。
有没有一种方法可以在运行Supertest的时候访问这个日志输出?
package.json:
"dependencies": {
"body-parser": "^1.17.1",
"express": "^4.15.2",
"mocha": "^3.2.0",
"mongoose": "^4.8.6"
},
"devDependencies": {
"nodemon": "^1.11.0",
"supertest": "^3.0.0"
}
发布于 2019-12-20 04:42:26
这是一个使用express错误处理中间件的supertest
的最小工作示例。
app.js
const express = require("express");
const app = express();
app.get("/", (req, res, next) => {
const error = new Error("make an error");
next(error);
});
app.use((err, req, res, next) => {
console.log("error: ", err.message);
res.status(422).send({ error: err.message });
});
module.exports = app;
app.test.js
const app = require("./app");
const request = require("supertest");
const { expect } = require("chai");
describe("42680896", () => {
it("should pass", (done) => {
request(app)
.get("/")
.expect(422)
.end((err, res) => {
if (err) return done(err);
expect(res.body).to.be.eql({ error: "make an error" });
done();
});
});
});
集成测试结果:
42680896
error: make an error
✓ should pass
1 passing (31ms)
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 94.74 | 50 | 100 | 100 | |
app.js | 100 | 100 | 100 | 100 | |
app.test.js | 90 | 50 | 100 | 100 | 11 |
-------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/42680896
https://stackoverflow.com/questions/42680896
复制