I am testing a fairly simple node API endpoint:
import { getRaces } from '@/services/races';
import { Request, Response, Router } from 'express';
import passport from 'passport';
export default (app: Router) => {
app.get('/races', passport.authenticate('jwt', { session: false }), async (req: Request, res: Response) => {
console.log(req);
if (req.user) {
res.status(200).json({ races: await getRaces() });
} else {
res.status(401).json({ error: 'Unauthorized' });
}
});
};
My initial mock appears to work as I expect, in the first test, a test user is successfully mocked, the test receives a 200 status, and also is able to confirm that the mocked data is returned properly.
import express from 'express';
import passport from 'passport';
import request from 'supertest';
import { getRaces } from '@/services/races';
import charactersRoute from './races';
jest.mock('@/services/races');
jest.mock('passport', () => ({
authenticate: jest.fn(() => (req, _res, next) => {
req.user = { id: 'test-user' }; // Mock authenticated user
next();
}),
}));
const app = express();
app.use(express.json());
const router = express.Router();
charactersRoute(router);
app.use(router);
describe('GET /races', () => {
it('should return 200 and a list of races when authenticated', async () => {
const mockRaces = [
{ id: 1, name: 'Elf' },
{ id: 2, name: 'Dwarf' },
];
(getRaces as jest.Mock).mockResolvedValue(mockRaces);
const response = await request(app).get('/races');
expect(response.status).toBe(200);
expect(response.body).toEqual({ races: mockRaces });
});
it('should return 401 when not authenticated', async () => {
(passport.authenticate as jest.Mock).mockImplementation(() => (_req, _res, next) => {
next();
});
const response = await request(app).get('/races');
expect(response.status).toBe(401);
expect(response.body).toEqual({ error: 'Unauthorized' });
});
});
However, it seems that the mockImplementation
function I've set up when trying to test Unauthenticated users doesn't get hit when the test is run and the initial passport mock is getting hit instead. When I console log both the initial mocked function as well as the mockImplementation
for passport.authenticate
I see that the initial mock is called twice.
I have tried the following in addition:
beforeEach
where I have attempted to reset the mock: `(passport.authenticate as jest.Mock).resetMockAs I see, it, the problem arises because the function you are trying to mock,
() => (req, _res, next) => {};
is actually a curried function. Outer function is called before the mockImplementation
call, at the moment of app initialization, somewhere within this block of code
const app = express();
app.use(express.json());
const router = express.Router();
charactersRoute(router);
app.use(router);
After that, only inner memoized function is called.
In order to achieve the desired result you should mock inner function instead. And then you should call mockImplementation
also for the inner function.
const authHandler = jest.fn((req, _res, next) => {
req.user = { id: 'test-user' }; // Mock authenticated user
next();
});
jest.mock('passport', () => ({
authenticate: jest.fn(() => authHandler),
}));
...
authHandler.mockImplementation((_req, _res, next) => {
next();
});