koehr.ing/content/til/2022-04-25.md
2024-06-17 09:55:36 +02:00

881 B

{ .title = "Jest mocks are ...different", .date = @date("2022-04-25T00:00:00"), .author = "koehr", .draft = false, .layout = "til.html", .description = "", .tags = [], }

If you want to mock an imported function in Jest in a way that allows you to check if it has been called, you can not do the seemingly straighforward:

// mock prefix necessary btw
const mockThatFunction = jest.fn(() => 'stuff')

jest.mock('@/path/to/module', () => ({
  thatFunction: mockThatFunction,
}))

// ...in test descriptions
expect(mockThatFunction).toHaveBeenCalled()

This way thatFunction will be undefined without anyone telling you why.

What you need to do instead:

import { thatFunction } from '@/path/to/module'

jest.mock('@/path/to/module', () => ({
  thatFunction: jest.fn(() => 'stuff'),
}))

// ...in test descriptions
expect(thatFunction).toHaveBeenCalled()