Recall how the user registration endpoint did not have any middleware. For the purposes of demonstrating how to test a middleware, we'll just be grabbing the isAuthenticated middleware that we created and test that instead.
File: src/middleware/auth.middleware.js
constglobalResponseDto=require('../responses/globalResponseDto')constisAuthenticated= (req, res, next) => {if (!req.session.user) {returnres.status(401).json(globalResponseDto({ status:'error', code:401, message:'Access denied: you must be logged in to access this API endpoint.', data:null, errors: ['You must be logged in.'] }) ) }next()}module.exports= isAuthenticated
Testing the middleware is a lot trickier than just a regular function. This reason why is because we are expected to stick to a particular function signature (req, res, next).
The answer to this is to mock out those particular parameters. The way to do it is to use jest.fn, which we will use to help us write out helpers like mockRequest, mockResponse, and mockNext functions.
Now watch as we pass the mockRequest, mockResponse, and mockNext functions into our isAuthenticated function. If everything goes well, then we should expect the next to be invoked.
test('Access granted, next() should be invoked in express',async () => {// 1. Arrangeconstreq=mockRequest({ first_name:'john' })constres=mockResponse()constnext=mockNext()// 2. ActawaitisAuthenticated(req, res, next)// 3. Assertexpect(next).toHaveBeenCalled()})
The Passing Test
Now for the failing test, we should expect the correct status code and output.
test('Access denied, respond with a status 401',async () => {// 1. Arrangeconstreq=mockRequest()constres=mockResponse()// 2. ActawaitisAuthenticated(req, res)// 3. Assertexpect(res.status).toHaveBeenCalledWith(401)expect(res.json).toHaveBeenCalledWith(globalResponseDto({ status:'error', code:401, message:'Access denied: you must be logged in to access this API endpoint.', data:null, errors: ['You must be logged in.'] }) )})