Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Unit Testing Middleware

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?

like image 879
Claudiu S Avatar asked Aug 07 '26 13:08

Claudiu S


1 Answers

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.

like image 78
B3rn475 Avatar answered Aug 09 '26 04:08

B3rn475



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!