How can I test authentication middleware with Jest - node.js

I'm learning nodejs and for the most part its going well. Im trying to learn how to do mocking in tests with jest. I've watched numerous tutorials but I cant seem to get my head around it.
I have this middleware that is used on protected routes...
import jwt from 'jsonwebtoken';
export default function (req, res, next) {
const token = req.header('x_auth-token');
if (!token) return res.status(401).json({ message: 'Access denied' });
try {
const verified = jwt.verify(token, process.env.TOKEN_SECRET);
req.user = verified;
next();
} catch (err) {
return res.status(400).send('Invalid Token');
}
}
From what I've read, I think the approach Im supposed to to take is something like this...
import verifyToken from '../middleware/verifyToken';
test('verifyToken', () => {
expect.assertions(1);
const res = {};
const req = {};
const next = (err) => expect(err).toBeFalsy();
verifyToken(req, res, next);
});
However this clearly doesnt work.
So how do I mock the request header with a token?

So if we comletely forget about what req, res are in the real world, obviously they are request and response, but lets just forget about that for now.
in your real code you have token = req.header("x_auth-token")
So in our test code, we need to have something in the req object that when called with those parameters returns what you want.
So I would say.
const req = {
header: jest.fn(() => 'myAuthToken')
}
the jest.fn() has mad a mock function and when it is invoked it will always return the string myAuthToken.
We can then check that the header function has been called with the correct params by adding
expect(req.header).toHaveBeenCalledWith("x_auth-token")
You are also going to need to mock jwt.verify as you are not testing that jwt.verify works as that will be covered it its own tests. You will want to make sure that you are using the response of that correctly
To do that take a look at this stack overflow question
And finally I would set next as a mock function
mockNext = jest.fn()
Then we can say in the test
expect(mockNext).toHaveBeenCalled()

So I was having trouble understandin how to mock functions. I did a bunch of googling based on on Ollie Pugh's answer and this is what I came up with.
import jwt from 'jsonwebtoken';
import verifyToken from '../middleware/verifyToken';
import { uIds } from './testdata/userTestData';
describe('verifyToken tests', () => {
const { uid1 } = uIds;
it('Should pass the userId to the request object if token is verified', () => {
const res = {};
const req = {
header: jest.fn(() => 'myAuthToken'),
};
const next = jest.fn();
const verify = jest
.spyOn(jwt, 'verify')
.mockReturnValueOnce({ userId: String(uid1) });
verifyToken(req, res, next);
expect(req.header).toHaveBeenCalledWith('x_auth-token');
expect(req.user).toEqual({ userId: String(uid1) });
expect(next).toHaveBeenCalled();
});
it('Should deny access if token is not present in header', () => {
const res = {
json(msg) {
expect(msg).toEqual({ message: 'Access denied' });
},
status(responseStatus) {
expect(responseStatus).toEqual(401);
return this;
},
};
const req = {
header: jest.fn(),
};
const next = jest.fn();
verifyToken(req, res, next);
expect(req.header).toHaveBeenCalledWith('x_auth-token');
expect(req.user).not.toEqual({ userId: String(uid1) });
});
it('Should deny access if token is invalid', () => {
const res = {
send(text) {
expect(text).toEqual('Invalid Token');
},
status(responseStatus) {
expect(responseStatus).toEqual(400);
return this;
},
};
const req = {
header: jest.fn(() => 123),
};
const next = jest.fn();
const verify = jest.fn();
verifyToken(req, res, next);
expect(req.header).toHaveBeenCalledWith('x_auth-token');
expect(req.user).not.toEqual({ userId: String(uid1) });
});
});
This passes the tests. However I'm not sure about the validity of the test.

Related

How to test next() in express middleware in JEST

After a lot of efforts i was not able to figure this one out and hence planned to get the help. I am using a middleware in my node+ express app which looks like :
import mainConfig from '../mainConfig/index';
const axios = require('axios');
module.exports = {
authHandler: (req, res, next) => {
return mainConfig.initialize().then(() => {
const apiUri = mainConfig.get('app.api');
if (apiUri) {
return axios.get(apiUri).then(response => {
next();
}).catch(error => {
res.redirect('/expired');
throw new Error(error);
});
}
}).catch(() => {
});
}
};
For this, I have written the test case in which I was able to mock the axios and my mainCongig module. Now, I want to test whether next() was called as the request was resolved for axios. Can someone help me with the same?
test case I have written is :
import mainConfig from '../mainConfig';
const axios = require('axios');
const middlewares = require('./check-auth');
jest.mock('axios');
describe('Check-Auth Token', () => {
it('should call the Sign In API when live Conf is initalized and have the API URL', () => {
mainConfig.get = jest.fn();
mainConfig.get.mockReturnValue('https://reqres.in/api/users');
mainConfig.initialize = jest.fn(() => Promise.resolve({ data: {} }));
const req = jest.fn(), res = { sendStatus: jest.fn() }, next = jest.fn();
axios.get.mockImplementation(() => Promise.resolve({ data: {} }));
middlewares.authHandler(req, res, next);
expect(next).toHaveBeenCalled(); // coming as not called.
});
});
You have to wait for the middleware to resolve. As you are returning a promise from your middleware, you can wait in the test with an await statement:
import mainConfig from '../mainConfig';
const axios = require('axios');
const middlewares = require('./check-auth');
jest.mock('axios');
describe('Check-Auth Token', () => {
it('should call the Sign In API when live Conf is initalized and have the API URL', async () => {
mainConfig.get = jest.fn();
mainConfig.get.mockReturnValue('https://reqres.in/api/users');
mainConfig.initialize = jest.fn(() => Promise.resolve({ data: {} }));
const req = jest.fn(), res = { sendStatus: jest.fn() }, next = jest.fn();
axios.get.mockImplementation(() => Promise.resolve({ data: {} }));
await middlewares.authHandler(req, res, next);
expect(next).toHaveBeenCalled(); // coming as not called.
});
});
Note that in order to be able to use the await keyword you need to define your test with async.
I'm not an expert, but as far as I know you are testing asynchronous code. So you have to use the done() keyword. Lookup this for more information: https://jestjs.io/docs/en/asynchronous

Jest/SuperTest Express integration tests - Can't set headers after they are sent. (when you call the same endpoint in multiple tests)

This one's killing me..
I'm writing integration tests for an Express (Typescript) app, using Jest and Supertest.
I have multiple tests for the same endpoint, to test responses from when a mocked service returns data correctly and when it rejects a promise with an Error object.
The tests run fine when each request() in each it() block hits a unique end point, but when endpoints are shared between blocks I get the following error:
Can't set headers after they are sent.
This is my test code:
let request = null;
let app = null;
const async = require('async');
import GError from '../../src/services/ErrorService';
const { list } = require('../../src/controllers/RecipeController');
let throwError: boolean = false;
let error = null;
const errorMsg: string = 'Something went wrong!';
const listData: Array<object> = [{id: 1, base: 'something'}];
jest.mock('../../src/services/RecipeService', () => {
return jest.fn().mockImplementation(() => ({
list: jest.fn(() => {
if (throwError) {
return Promise.reject(error);
}
return Promise.resolve(listData);
})
}));
});
beforeEach(() => {
request = require('supertest');
app = require('../../src/app');
});
afterEach( ( done ) => {
throwError = false;
error = null;
app.close( () => {
delete require.cache[require.resolve('../../src/app')];
done();
});
});
describe('Root Path', () => {
it('should return a welcome message', (done) => {
request(app)
.get('/')
.end((err, res) => {
expect(res.text).toEqual('Test API.');
expect(res.statusCode).toBe(200);
done();
});
});
});
describe('Recipe List', () => {
it('should call controller and return correct response when successful or error is thrown in service', (done) => {
const path: string = '/recipes/list';
request(app)
.get(path)
.end((err, res) => {
expect(JSON.parse(res.text)).toEqual({
recipes: listData
});
done();
});
});
it('should return an error response if service rejects promise', (done) => {
throwError = true;
error = new GError(errorMsg);
const path: string = '/recipes/list';
request(app)
.get(path)
.end((err, res) => {
expect(JSON.parse(res.text)).toEqual({
errors: {
message: errorMsg
}
});
done();
});
});
});
I think I need to reset the app in between tests, which is what I'm trying to achieve with:
beforeEach(() => {
request = require('supertest');
app = require('../../src/app');
});
But with no joy. Can anyone shine a light?
UPDATE:
Here's the controller method the route hits:
exports.list = async (req, res, next) => {
const recipes: IRecipeList = await recipeService.list().catch(err => {
return next(err);
});
const response: IRecipeListResponse = {recipes};
res.status(200).json(response);
};
SOLVED:
So it turned out to be nothing to do with Jest / Superagent (I was sure it was to do with one of these). Strangely though I only get this error in the context of running integration tests, there is no error when hitting the end point in Postman - which was super confusing.
PROBLEM:
exports.list = async (req, res, next) => {
const recipes: IRecipeList = await recipeService.list().catch(err => { . //this doesn't stop the execution past this await
return next(err);
});
//this still gets processed if the service rejects the promise
const response: IRecipeListResponse = {recipes};
res.status(200).json(response);
};
SOLUTION:
exports.list = async (req, res, next) => {
let error = false;
const recipes: IRecipeList = await recipeService.list().catch(err => {
error = true;
return next(err);
});
if (error) {
return;
}
const response: IRecipeListResponse = {recipes};
return res.status(200).json(response);
};
This error occurs when you send response more than once.

Jest Memory Leak testing Express Middleware

I am attempting to unit test my authentication middleware for Express. The middleware is quite simple and can be viewed below in its entirety:
const admin = require('./../config/firebase/firebase');
// Models - User
const User = require('./../models/user');
const auth = async (req, res, next) => {
try {
// The Authorization Bearer Token sent in the header of the request needs to be decoded.
const token = req.header('Authorization').replace('Bearer ', '');
const decoded = await admin.auth().verifyIdToken(token);
// Finding that user in the database by their Firebase UID.
const user = await User.findOne({ _id: decoded.uid });
// If that user does not exist, we'll throw an error.
if (!user) {
throw new Error();
}
// Making the user accessible to the endpoint.
req.user = user;
// Proceed
next();
} catch (e) {
// HTTP 404 Unauthorized Response Status
res.status(401).send({ error: 'Please authenticate.' });
}
}
module.exports = auth;
Since the Firebase Admin SDK returns an object that contains the user's UID as a property, for the purpose of my tests, I create a "fake token" which is just an object with a UID property. I then mock the Admin SDK such that it returns whatever was passed in, as so:
module.exports = {
auth() {
return this;
},
verifyIdToken(token) {
return JSON.parse(token);
},
initializeApp(app) {
},
credential: {
cert() {
}
}
}
Since the auth middleware expects to find a user in the test database, I have to configure that as Jest Setup in the beforeAll hook:
const userOneToken = JSON.stringify({ uid: 'example UID' });
const userOne = {
_id: 'example UID',
// ...
};
beforeAll(async () => {
await User.deleteMany();
await User.save(userOne);
app.use(auth).get('/', (req, res) => res.send());
});
This means that the middleware will always be able to get a UID in return, which can be used to find a test user in the test database.
The test suite itself, after importing my Express Application, is quite simple, with just three tests:
const auth = require('./../../src/middleware/auth');
describe('Express Auth Middleware', () => {
test('Should return 401 with an invalid token', async () => {
await request(app)
.get('/')
.set('Authorization', 'Bearer 123')
.send()
.expect(401);
});
test('Should return 401 without an Authorization Header', async () => {
await request(app)
.get('/')
.send()
.expect(401);
});
test('Should return 200 with a valid token', async () => {
await request(app)
.get('/')
.set('Authorization', `Bearer ${userOneToken}`)
.send()
.expect(200);
});
});
It appears, however, that the tests are leaking memory (apparent by calling with the --detectLeaks flag). Additionally, it seems Jest is also finding an open handle left behind by the last test. Running the suite with the --detectOpenHandles flag returns a TCPSERVERWRAP error on the get request of the last test.
Potential solutions were proposed in this GitHub issue, but none of them worked for me.
Any help solving this issue would be much appreciated, for all my test suites are leaking memory because they rely on Supertest. Thank you.

How to test response data from Express in Jest

I'm writing unit tests for separate middleware functions in Node/Express using Jest.
A simple example of the middleware:
function sendSomeStuff(req, res, next) {
try {
const data = {'some-prop':'some-value'};
res.json(data);
next();
} catch (err) {
next(err);
}
}
And a sample of my test suite:
const httpMocks = require('node-mocks-http');
const { sendSomeStuff } = require('/some/path/to/middleware');
describe('sendSomeStuff', () => {
test('should send some stuff', () => {
const request = httpMocks.createRequest({
method: 'GET',
url: '/some/url'
});
let response = httpMocks.createResponse();
sendSomeStuff(request, response, (err) => {
expect(err).toBeFalsy();
// How to 'capture' what is sent as JSON in the function?
});
});
});
I have to provide a callback to populate the next parameter, which is called in the function. Normally, this would 'find the next matching pattern', and pass the req and res objects to that middleware. However, how can I do this in a test set-up? I need to verify the JSON from the response.
I don't want to touch the middleware itself, it should be contained in the test environment.
Am I missing something here?
Found a fix!
Leaving this here for someone else who might struggle with the same.
When returning data using res.send(), res.json() or something similar, the response object (from const response = httpMocks.createResponse();)
itself is updated. The data can be collected using res._getData():
const httpMocks = require('node-mocks-http');
const { sendSomeStuff } = require('/some/path/to/middleware');
describe('sendSomeStuff', () => {
test('should send some stuff', () => {
const request = httpMocks.createRequest({
method: 'GET',
url: '/some/url'
});
const response = httpMocks.createResponse();
sendSomeStuff(request, response, (err) => {
expect(err).toBeFalsy();
});
const { property } = JSON.parse(response._getData());
expect(property).toBe('someValue');
});
});
});
I did a different way by utilising jest.fn(). For example:
if you wanna test res.json({ status: YOUR_RETURNED_STATUS }).status(200);
const res = {};
res.json = jest.fn(resObj => ({
status: jest.fn(status => ({ res: { ...resObj, statusCode: status }
})),
}));
Basically, I mock the res chain methods(json and status).
That way you can do expect(YOUR_TEST_FUNCTION_CALL).toEqual({ res: { status: 'successful', statusCode: 200 }}); if your response structure is like that.

How to test express middleware that depends on other vendor middleware?

I wanna test a middleware function that inside calls a vendor middleware function. The middleware is:
const expressJwt = require('express-jwt');
const validateJwt = expressJwt({ secret: 'whatever' });
exports.isAuthenticated = (req, res, next) => {
if (req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = `Bearer ${req.query.access_token}`;
}
validateJwt(req, res, next);
};
I've tried to create a sinon.spy() object and pass it as next parameter, but is not called apparently.
Another approach I've tried is to check if exists req.user, since the purpose of the express-jwt middleware is to validate and attach user to the req object. No luck with this neither.
I've seen the existence of chai-connect, but not sure how to use it.
Any ideas? Highly appreciate it!
I finally managed to do it with proxyquire and chai-connect:
In your mocha config:
chai.use(require('chai-connect-middleware'));
global.connect = chai.connect;
In your test:
describe('isAuthenticated', () => {
// Wrap call to chai.connect into a function to use params and return a Promise
const mockedMiddleware = (changeSecret) => {
let oldToken;
if (changeSecret) {
oldToken = acessToken;
acessToken = 'blabalblalba';
}
return new Promise((resolve, reject) => {
connect.use(middleware.isAuthenticated)
.req(req => {
req.query = { access_token: acessToken };
})
.next((res) => {
acessToken = oldToken;
if (res && res.status === 401) {
reject(res.message);
} else {
resolve();
}
})
.dispatch();
});
};
it('should validate correctly', () =>
mockedMiddleware().should.be.fulfilled
);
it('should not validate', () =>
mockedMiddleware(true).should.be.rejected
);
});

Resources