node.js - NodeJS and Express -- How to mock token authentication middleware for testing? -
i'm making rest api uses jwts authentication, test endpoints want mock middleware verifys jwts.
i've defined middleware checking token:
// middlewares/auth.js njwt = require('njwt'); nconf = require('nconf'); module.exports = { verifytoken: function(req, res, next) { // check header or url parameters or post parameters token var token = req.body.token || req.query.token || req.headers['x-access-token']; // decode token if (token) { // verifies secret , checks exp njwt.verify(token, nconf.get("auth:secret"), function(err, verifiedjwt) { if (err) { return res.json({ success: false, message: 'failed authenticate token.' }); } else { // if good, save request use in other routes req.userid = verifiedjwt.body.sub; next(); } }); } else { // if there no token // return error return res.status(403).send({ success: false, message: 'no token provided.' }); } } }
then in routers can import , use middleware on protected endpoints
// routes/someroutes.js var router = require('express').router(); var verifytoken = require('../middlewares/auth').verifytoken; router.use(verifytoken); // define routes
now want mock middleware out can test endpoints without need valid token. i've tried doing using chai/mocha/sinon don't have luck
// tests/someroutes.js var auth = require('../middlewares/auth'); var sinon = require('sinon'); describe('someroute', function() { var verifytokenstub; before(function (done) { verifytokenstub = sinon.stub(auth, 'verifytoken', function(req, res, next) { req.userid='test-id'; next(); }); }); });
but still calling original verifytoken method. appreciated!
- change
middlewares/auth.js
file checkprocess.env.node_env
.
example:
// middlewares/auth.js ... // decode token if (token || process.env.node_env === 'test') {//changes in string // verifies secret , checks exp njwt.verify(token, nconf.get("auth:secret"), function(err, verifiedjwt) { ...
if use supertest or package same functionality, run mocha environment variable -
node_env=test mocha
.if testing application full run, should start environment variable -
node_env=test npm start
.
it's not mocking, hope you.
Comments
Post a Comment