3

I have an api with a middleware function which I use to filter incoming requests. The functions checks the present of a token in the header, then makes two calls to the database, one to check the token and one to get some information and pass it on to the request object, if the 1st call was successful.

I am struggling to understand how to unit test this functions, by mocking up the request object and also the database calls.

middleware.js

exports.checkToken = function (req, res, next) {
  if (!req.get('token')) {
      return res.status(400).json('Bad request');
  }

  var token = req.get('token'); //get token from the header 

  User.findOne({'token': token}, function(err, user) {
      // skipped error checking or no user found
      Account.findOne({'_id': user.account}, function(err, account) {
          // skipped error checking or no account found
          req.somevalue = account;
          return next();
      });
  });
};

Currently I am using mocha, chai and sinon and was thinking of the following:

  • mock User.findOne and Account.findOne using sinon.stub()

  • not really sure what to do about the req, res and next objects. How to emulate these?

1 Answer 1

1

I think the best choice is to use supertest.

https://www.npmjs.com/package/supertest

This package allow to run tests that emulate the full request cicle on the application.

Sign up to request clarification or add additional context in comments.

3 Comments

I've used this package before, but was wondering if there was any other way of unit testing middleware, and NOT the whole endpoint, as that would more oriented towards integration testing.
A middleware is nothing more than a function. So you can apply standard unit testing to that. Request can be plain old javascript objects with just the properties required to the test ends.
I'll probably do that and come back with an ANS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.