Search code examples
node.jsrestmocha.jssupertest

How to test an express rest api with header parameters using mocha and supertest?


I have to test my rest api. Some routes require a value in the http requests headers for the user authentication token.

I have separated my interesting bussiness logic in pure javascript code but I can't find a way to test the routes that require a token in the headers of the http request.

Any other alternatives to mocha and/or supertest are welcome.


Solution

  • With supertest, you can set a header parameter with the set keyword :

    api.get('/aroute/')
    ...
    .set('headerParameterName', value)
    ...
    

    Here is an example of testing a express server API with token authorization using supertest :

    app.js:

    var express = require('express');
    var app = express();
    var jwt = require('jsonwebtoken');
    var expressJwt = require('express-jwt');
    
    var secret = 'my-secret';
    
    app.get('/get-token', function(req, res) {
      var token = jwt.sign({foo: 'bar'}, secret);
      res.send({token: token});
    });
    
    app.post(
      '/test',
      expressJwt({
        secret: secret
      }),
      function(req, res) {
        res.send({message: 'You could use the route!'});
      }
    );
    
    app.use(function(err, req, res, next) {
      res.status(err.status || 500).send({error: err.message});
    });
    
    app.listen(4040, function() {
      console.log('server up and running at 4040 port');
    });
    
    module.exports = app;
    

    test.js:

    var request = require('supertest');
    var app = require('./app.js');
    
    describe('Test Route with Token', function() {
      var token = '';
    
      before(function(done) {
        request(app)
          .get('/get-token')
          .end(function(err, res) {
            var result = JSON.parse(res.text);
            token = result.token;
            done();
          });
      });
    
      it('should not be able to consume the route /test since no token was sent', function(done) {
        request(app)
          .post('/test')
          .expect(401, done);
      });
    
    
      it('should be able to consume the route /test since token valid was sent', function(done) {
        request(app)
          .post('/test')
          .set('Authorization', 'Bearer ' + token)
          .expect(200, done);
      });
    });