javascript - How would you test this route code? -
i have following route code. user
sequelize model, jwt
creating jwt token.
i want avoid hitting db, want stub out both dependencies.
user.create returns promise. want able assert res.json being called. think mock user.create should return real promise , fulfill promise.
i want assert res.json
called. test method exiting before promise fulfilled. i'm not returning promise route, can't return it
in test.
given want mock dependencies, please show me how test this?
if have suggestion how how better structure 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 files mocking up: user, jwt, created 2 additionals route, , test itself.
you can see here files, if want run need first install mocha , q:
npm install mocha npm install q
and run: mocha
so created object called res , added method called json, when json method called code, know 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 module, , routehandler function interface function (req, res) being returned module.
Comments
Post a Comment