在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时,但在运行测试时,中间件正确地将错误显示为对主体的响应。
我有2个终端窗口打开,运行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"
}
最佳答案
这是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