Spencer Kormos Spencer Kormos - 1 year ago 94
Javascript Question

Testing for next(err) with supertest and Express JS

In a route or middleware in Express, you can skip the remaining call chain by invoking next(err) where err is any object. This is pretty straightforward from the docs.

When testing with SuperTest, this workflow does not seem to be supported. The only error result from the middleware to supertest, is that the text on the response is set to

[object Object]

For example:

const request = require('supertest');
const app = express();
app.use( (req, res, next) => next({ error: "ErrorCode" }) );
.end(function(err, res) {
// err == undefined
// res.text === '[object Object]'

Is there a way with supertest to validate the object passed to the next() callback?

I obviously could use sinon+chai or jasmine to straight unit test the code, but I'm curious if this is possible with just supertest, and maybe even a supporting bespoke middleware after the testable unit.

Answer Source

Supertest works at the HTTP response level, so it can only check the status, headers, body of the response itself based on the HTTP message. It cannot check javascript-level details about the code inside the express app (supertest can actually check arbitrary HTTP servers written in any language, it just has some convenience code for express).

Thus first I'd write an error handler middleware that translates your error objects (which really should be Error instances instead of plain objects), sets the proper status code, content type, body, etc. Then make your supertest associations for those attributes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download