使用 'supertest' 测试期间快速中间件控制台输出



此中间件在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)
})
...

中间件正确地将错误作为对身体的响应,使用邮递员的响应,但在运行测试时却没有。

我有2个终端窗口打开运行npm运行:teststart,在运行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的最小工作示例,可与Express错误处理程序中间件一起使用。

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-chai-sinon-codelab/tree/master/master/src/stackoverflow/42680896

最新更新