I am writing an Express middleware component that'll run on Node 4, which has limited ES2015 support.
The fundamental purpose of this component is to verify JSON web tokens, using the jsonwebtoken module. Here is said component:
const jwt = require("jsonwebtoken");
module.exports = {
ensureAuthenticated: function(req, res) {
return new Promise(function(resolve, reject) {
const token = req.query.token;
if (!token) {
return reject({
status: 401
});
} else {
jwt
.verify(token, "secret", function(err, decoded) {
if (err) {
return reject({
status: 401
});
} else {
req.user = decoded;
resolve();
}
});
}
});
}
};
I also wrote some unit tests, using Mocha and Chai:
const chai = require("chai");
const proxyquire = require("proxyquire");
const httpMocks = require("node-mocks-http");
const expect = chai.expect;
suite("ensureAuthenticated", function() {
test("should return 401 when token is \"undefined\"", function() {
const sut = require("../../middleware");
const req = httpMocks.createRequest();
return sut
.ensureAuthenticated(req)
.catch(function(outcome) {
expect(outcome.status).to.equal(401);
});
});
test("should return 401 when token is invalid", function() {
const jsonwebtoken = { };
jsonwebtoken.verify = function(token, secret, cb) {
cb({});
};
const req = httpMocks.createRequest({
query: {
token: "bar"
}
});
const sut = proxyquire("../../middleware", {
jsonwebtoken: jsonwebtoken
});
return sut
.ensureAuthenticated(req)
.catch(function(outcome) {
expect(outcome.status).to.equal(401);
});
});
test("should add decoded data to req object when token is valid", function() {
const decoded = {
username: "dummy username"
};
const jsonwebtoken = { };
jsonwebtoken.verify = function(token, secret, cb) {
cb(undefined, decoded);
};
const req = httpMocks.createRequest({
query: {
token: "dummy token"
}
});
const sut = proxyquire("../../middleware", {
jsonwebtoken: jsonwebtoken
});
return sut
.ensureAuthenticated(req)
.then(function() {
expect(req.user).to.equal(decoded);
});
});
});
As you can see, the component returns a Promise
, which makes it unit-testable. I got the idea from this talk.
I would please like to hear any thoughts you have about the quality of my tests. I am also interested in any general criticism.