0

I'm trying to mock out a single function in a module with Jest and assert that I have called it with certain parameters. I have a file that roughly looks like so:

export const f = () => {
  ...
}
export const g = () => {
  ...
  f(...)
}
export const h = () => {
  ...
  g(...)
}

I'm trying to test out functions g and h, and one the assertions I'm trying to write is that f gets called with certain parameters when calling g and h. So in my tests, I want to mock out f and be able to assert what it was called with. However, when I do something like this in my tests:

import f, g, h from 'module'

jest.mock('module', () => {
  const original = jest.requireActual('module')
  
  return {
    ...original,
    f: jest.fn()
  }
})
test('g calls f correctly', () => {
  g()
  // I want to assert that f was called with some parameters
})

I have no reference to f, and it seems like when g gets called in the test, the actual function f is being called rather than a mock. What do I need to change here to get this working?

mp94
  • 1,209
  • 3
  • 11
  • 23
  • (Specifically https://stackoverflow.com/a/70066090/3001761. TL;DR: don't.) – jonrsharpe Jun 20 '22 at 07:03
  • That thread does help, the top answer is what I went with. I can see why it might not be ideal to mock out a function from the same module, however due to some complications with async functions also making it hard to test, this seemed like the best solution. – mp94 Jun 21 '22 at 00:51

1 Answers1

-1

It looks like you're on the right path. I'll recommend you try one of the following examples:

import { f, g } from './module'

jest.mock('./module', () => {
  const actual = jest.requireActual()

  return { ...actual, f: jest.fn() }
})

test('g calls f correctly', () => {
  g()
  expect(f).toHaveBeenCalled()
})

If you get an error saying that f should be a mock function, you could try this:

import { g } from './module'

// Create a reference of the mocked function to use later in the test.
// The name must start with "mock". It's a Jest rule.
const mockedF = jest.fn()

jest.mock('./module', () => {
  const actual = jest.requireActual()

  return { ...actual, f: mockedF }
})

test('g calls f correctly', () => {
  g()
  expect(mockedF).toHaveBeenCalled()
})
Ricky Almeida
  • 89
  • 1
  • 4