3

So right now I have something like this (which doesn't work)

import app from '../src/app';

beforeAll(() =>
  jest.mock('../src/middleware/auth', () => (req: Request, res: Response, next: NextFunction) => {
    req.user = {};
    return next();
  });

afterAll(() =>
  jest.unmock('../src/middleware/auth'));

and then my test as usual:

describe('POST /v1/protected-route', () => {
  it('should return 200 OK', async () => {
    await request(app)
      .get('/v1/protected-route')
...

in ../src/app I'm importing ./middleware/auth and adding it like so app.use(auth())

I still keep getting 401s and it looks like the mock is not getting used here.

Zia
  • 2,735
  • 3
  • 30
  • 27

1 Answers1

2

I solved a similar problem I was having by moving the jest.mock() out of the beforeAll(). It appears that jest.mock() is hosted to the top of its scope, not the file itself. So since you are importing your app at the top of the file (which then requires your middleware) the middleware is still your original rather than the mock, which gets stuck in the beforeAll() function.

I'm new to jest so I might be misunderstanding something important...

tsummer2
  • 56
  • 4