How would you test this route code?
I have the following route code. User
is sequelize , jwt
designed to create JWT .
I want to avoid hitting the db, so I want to stub both dependencies.
User.create returns a promise. I want to be able to assert that res.json is actually being called. I think my User.create should return a real promise and keep that promise.
I want to assert what is being called res.json
. My test method comes out before the promise is fulfilled. I am not returning a Promise from my route, so I cannot return it from it
in my test.
Given that I want to mock dependencies, please show me how you will experience this?
If you have any suggestion on how best to 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) {
});
};
};
source to share
I created some files for mockery: User, jwt, also created two additional files for your route and the test itself.
You can see all files here , if you want to run you need to install mocha and q first:
npm install mocha
npm install q
and mileage: mocha
so I created an object named res and added a json method, so when this json method is called from your code, we know the test 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 variable route represents your module, and routeHandler is a function with interface (req, res) returned by your module.
source to share