How would you test this route code?

195 Views Asked by At

I have the following route code. User is a sequelize model, jwt is for creating a JWT token.

I want to avoid hitting the db, so I want to stub out both dependencies.

User.create returns a Promise. I want to be able to assert that res.json is actually being called. I think my mock User.create should return a real promise and fulfill that promise.

I want to assert that res.json is called. My test method is exiting before the Promise is fulfilled. I'm not returning the Promise from my route, so I can't return it from the it in my test.

Given that I want to mock the dependencies, please show me how you would test this?

If you have a suggestion how to how better structure this code please let me know.

module.exports = function(User, jwt) {
  'use strict';

  return function(req, res) {
    User.create(req.body)
    .then(function(user) {
      var token = jwt.sign({id: user.id}); 
      res.json({token: token});
    })
    .catch(function(e) {
    });
  };
};
1

There are 1 best solutions below

1
On BEST ANSWER

I created some files for mocking up: User, jwt, also created two additionals for your route, and the test itself.

You can see here all the files, if you want to run you need first install mocha and q:

npm install mocha
npm install q

and the run: mocha

so I created an object called res and added a method called json, so when this json method is called from your code, we will know that the test has passed.

var jwt = require('./jwt.js');
var User = require('./user.js');
var route = require('./route.js');

describe('Testing Route Create User', function () {
  it('should respond using json', function (done) {
    var user = {
      username: 'wilson',
      age: 29
    };

    var res = {};
    var req = {};
    var routeHandler = route(User, jwt);

    req.body = user;

    res.json = function (data) {
      done();
    }

    routeHandler(req, res);
  });
});

the route variable represents your module, and routeHandler is the function with the interface function (req, res) that is being returned by your module.