简体   繁体   中英

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" }) );
request(app).get('/')
  .expect(500)
  .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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM