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) {
});
};
};
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:
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.
the route variable represents your module, and routeHandler is the function with the interface function (req, res) that is being returned by your module.