Consider the setup provided below:
const express = require("express");
const app = express();
app.get("/", function(req, res, next) {
// deliberately trigger an error
return next("my error");
});
// created this middleware for demonstration purposes,
// approach should generally work for default error handling in express too
app.use(function(error, req, res, next) {
if (error) {
res.status(500).send({ error });
throw new Error(error); // <- how to verify this?
}
next();
});
app.listen(8080, function() {
console.log("server running on 8080");
}); //the server object listens on port 8080
And for testing purposes:
const request = require("supertest");
const app = require("../../app.js");
const spy = jest.spyOn(global.console, "error").mockImplementation();
it("triggers an error", async done => {
const res = await request(app).get("/");
expect(res.status).toBe(500);
expect(res.error.text).toContain("my error");
expect(spy).toHaveBeenCalled(); // none...
done();
});
I have set up a Codesandbox with this sample code. Unsure about executing a node test within it though.