最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jest mockImplementation doesn't appear to override initial mocked module's function - Stack Overflo

programmeradmin4浏览0评论

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:

  • Importing passport after mocking passport in case there was an issue with scope. Though my prettier and eslint plugins re-order the import to the top of the file.
  • Adding a beforeEach where I have attempted to reset the mock: `(passport.authenticate as jest.Mock).resetMock

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:

  • Importing passport after mocking passport in case there was an issue with scope. Though my prettier and eslint plugins re-order the import to the top of the file.
  • Adding a beforeEach where I have attempted to reset the mock: `(passport.authenticate as jest.Mock).resetMock
Share Improve this question asked Jan 18 at 1:40 mealeystmealeyst 34 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

As 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();
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论