Node.js - Unit Testing Middleware -
i have api middleware function use filter incoming requests. functions checks present of token in header, makes 2 calls database, 1 check token , 1 information , pass on request object, if 1st call successful.
i struggling understand how unit test functions, mocking request object , database calls.
middleware.js
exports.checktoken = function (req, res, next) { if (!req.get('token')) { return res.status(400).json('bad request'); } var token = req.get('token'); //get token header user.findone({'token': token}, function(err, user) { // skipped error checking or no user found account.findone({'_id': user.account}, function(err, account) { // skipped error checking or no account found req.somevalue = account; return next(); }); }); };
currently using mocha, chai , sinon , thinking of following:
mock user.findone , account.findone using sinon.stub()
not sure req, res , next objects. how emulate these?
i think best choice use supertest.
https://www.npmjs.com/package/supertest
this package allow run tests emulate full request cicle on application.
Comments
Post a Comment