How to mock middleware in Express to skip authentication for unit test?

You can use sinon to stub isAuthenticated method, but you should do that before a reference to auth.isAuthenticated is set as a middleware, so before you require the index.js and app is created. Most likely you would want this in a beforeEach hook:

var app;
var auth;

beforeEach(function() {
  auth = require('../wherever/auth/auth.service');
  sinon.stub(auth, 'isAuthenticated')
      .callsFake(function(req, res, next) {
          return next();
      });

  // after you can create app:
  app = require('../../wherever/index');
});

afterEach(function() {
  // restore original method
  auth.isAuthenticated.restore();
});

it('it should return a 200 response', function(done) {
  request(app).post('/subscriptions/sync')
  .set('Authorization','Bearer '+ authToken)
  .send({receipt: newSubscriptionReceipt })
  .expect(200,done);
});

Please note that even after auth.isAuthenticated is restored, existing app instance will have stub as a middleware, so you need to create another app instance if you need to get an original behavior by some reason.

Update: there is a way to alter middleware’s behavior without recreating the server each time as explained in another SO answer.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)