Node.js - Unit Testing Middleware

I have an api with a middleware function that I use to filter incoming requests. The functions check for the real token in the header, then make two calls to the database, one to check the token and one to get some information and pass it to the request object if the first call was successful.

I am trying to figure out how to unit test these functions by mocking the request object and 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();
      });
  });
};

      

I am currently using mocha , chai and sinon and thought about the following:

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

  • not sure what to do with req, res and the following objects. How do I simulate these?

+3


source to share


1 answer


I think the best choice is to use a supertest.

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



This package allows you to run tests that emulate a full cicle request in your application.

+1


source







All Articles