0

I'm trying to mock a simple exported function in a test with Jest. The problem is that the mocked function is not being called.

example.ts


export const exampleFn = () => {
  return 'example'
}

example.spec.ts


import * as example from '@/example'
import { jest } from '@jest/globals'

jest.mock('@/example', () => ({
  __esModule: true, // this property makes it work
  ...jest.requireActual<typeof import('@/example')>('@/example'),
  exampleFn: jest.fn(() => 'mockedExample'),
}))

describe('example', () => {
  it('returns example', () => {
    const result = example.exampleFn()
    expect(result).toBe('mockedExample')
  })
})

afterEach(() => {
  jest.clearAllMocks()
})

output

 FAIL  src/__tests__/example.spec.ts
  ● example › returns example

    expect(received).toBe(expected) // Object.is equality

    Expected: "mockedExample"
    Received: "example"

What I'm expecting is that the mocked function should be called. I followed the jest official docs

0

Browse other questions tagged or ask your own question.