5

This middleware is not showing up when running in 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 });
});

I just spent a silly amount of time trying to find this error:

Driver.findByIdAndDelete(driverId) // Remove NOT Delete
  .then(driver => {
    res.status(204).send(driver)
})
...

The middleware properly showed the error as a response to the body, when using Postman, but not while running the tests.

I have 2 terminal windows open running npm run: test and start and nothing showed up here helpful until running Postman.

Is there a way to access this log output even when running 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"
  }
Lin Du
  • 88,126
  • 95
  • 281
  • 483
Michael Bruce
  • 10,567
  • 2
  • 23
  • 31

1 Answers1

0

Here is a minimal working example for supertest works with express error handler middleware.

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();
      });
  });
});

Integration test result:

 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 |
-------------|----------|----------|----------|----------|-------------------|

Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/42680896

Lin Du
  • 88,126
  • 95
  • 281
  • 483