I want to test the code below, but i'm unsure how to test this function since it returns a function with parameters. You can see in the image that i'm trying to achieve 100% test coverage and to do that I need a test that gets into the returned function.
const jwt = require('express-jwt')
function validateJwt (tokenConfig) {
if (!tokenConfig || !tokenConfig.secret) {
throw new TypeError('tokenConfig param must be defined and have attribute "secret"')
}
return (req, res, next) => {
jwt(_.extend({}, tokenConfig, {
requestProperty: 'tkn',
getToken: ReqHelpers.getEitherTkn
}))
}
}
Test method which obviously fails with the error AssertionError: expected [Function] to be true
it('should succeed', () => {
let result = middleware.validateJwt({secret: 'foo'})
expect(result).to.be.true
})
For this kind of test, what we can do is to spy on jwt function call and checking its arguments.
Updated:
since express-jwt
return function, we need to involve proxyquire
to spy the function. Ref: https://github.com/thlorenz/proxyquire
You can do something like this:
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const jwtSpy = sinon.spy();
const middleware = proxyquire('./middleware', { 'express-jwt': jwtSpy }); // 'express-jwt' comes from your require statement for this package
it('should call jwt', () => {
const req = sinon.spy();
const res = sinon.spy();
const next = sinon.spy();
middleware.validateJwt({secret: 'foo'})(req, res, next);
expect(jwtSpy.called).to.be.ok;
expect(jwtSpy.calledWithArg({ secret: 'foo', requestProperty: 'tkn'}).to.be.ok; // for checking the arguments
})
Hope it helps
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments