4

I am attempting to test middleware functions in my Express application using supertest and nock, but am having issues where the routes I have setup are checked by an earlier piece of middleware to ensure a session property exists on the incoming req object.

I need to somehow mock out the session object prior to running the tests, but am unsure how to approach this. First let me share some code:

router.js

app.use('/api', helpers.hasAccessToken, require('./routes.js'));

routes.js

router.route('/*')
  .get(routesController.fetch)

helpers.js

module.exports.hasAccessToken = function(req, res, next) {
  if(req.session.accessToken){
    next();
  } else {
    res.status(401).send('LOGIN_SESSION_ENDED');
  }
};

routesController.js

module.exports.fetch = function(req, res) {
  var options = helpers.buildAPIRequestOptions(req);
  request(options, function(err, response, body){
    res.status(response.statusCode).send(body);
  });
};

routesController.spec.js

var app = require('./index.js'),
  request = require('supertest')(app),
  expect = require('chai').expect,
  nock = require('nock');


describe('GET requests', function(){
  beforeEach(function(){
    nock('https://10.105.195.12:8243')
      .get('/v1/schemes')
      .reply(200, {foo:'bar'});
  });
  it('should return a 200 HTTP status code', function(done){
    request
      .get('/api/schemes')
      .end(function(err, res){
        expect(res.status).to.equal(200);
        done();
      });
  });
});

My test fails as the value for res.status is 401. I am using express-session, but I wondered if there was some way I could get at the req.session object in my test suite and set the value of the accessToken property prior to running any of the tests.

Can anyone offer any advice\thoughts please?

Thanks

4

1 回答 1

5

req.session让我们为具有我们控制的值的对象创建一些存根。

var app = require('./index.js'),
  request = require('supertest'), // no longer app here as we want to call parentApp
  expect = require('chai').expect,
  nock = require('nock');

describe('GET requests', function(){
  var parentApp;

  beforeEach(function(){
    parentApp = express();
    parentApp.use(function(req, res, next) { // lets stub session middleware
      req.session = {};
      next();
    })
    parentApp.get('/api', function(req, res, next) {
      req.session.accessToken = true;  // and provide some accessToken value
      next();
    })
    parentApp.use(app);
    nock('https://10.105.195.12:8243')
      .get('/v1/schemes')
      .reply(200, {foo:'bar'});
  });

  it('should return a 200 HTTP status code', function(done){
    request(parentApp) // we are testing now app through parentApp and stubbed middleware
      .get('/api/schemes')
      .end(function(err, res){
        expect(res.status).to.equal(200);
        done();
      });
  });
});
于 2016-11-16T15:56:58.140 回答