reactjsjestjscreate-react-app

jest.fn() inside jest.mock() returns undefined


I have a simple "util" module with a default export and 2 named exports.

const foo = () => 'foo'
export default foo
    
export const bar = () => 'bar'
export const baz = () => 'baz'

In my test, I'm mocking it like that:

jest.mock('./util', () => ({
  __esModule: true,
  default: jest.fn(() => 'mocked foo'),
  bar: jest.fn(() => 'mocked bar'),
  baz: jest.fn(() => 'mocked baz'),
}))

describe('util', () => {
  //...
})

In my component, when I call foo(), bar() or baz(), I received undefined. But everything is working if I remove jest.fn() like that:

jest.mock('./util', () => ({
  __esModule: true,
  default: () => 'mocked foo',
  bar: () => 'mocked bar',
  baz: () => 'mocked baz',
}))

My example is very close to the one in the Jest docs.

I'm using React (CRA) and TypeScript.

I know there are different ways to mock a module but I'm curious to understand the issue that I'm facing.

What am I doing wrong?


Solution

  • I ran into the same issue (also running CRA) and found this might be the cause:

    https://github.com/facebook/jest/issues/9131#issuecomment-668790615

    A little late here, but I was just having this exact issue. I discovered that someone had added resetMocks: true to the jest.config.js file. This means that the implementations of mock functions are reset before each test. So in our case, the mock function was being included in the mocked module at test runtime, but that mock had been reset, so it returned undefined.

    Regarding the original issue build environment, it looks like react-scripts does indeed add resetMocks: true into the jest config. (https://github.com/facebook/create-react-app/blob/main/packages/react-scripts/scripts/utils/createJestConfig.js#L69) But you can override it on the jest key of your package.json. (https://github.com/facebook/create-react-app/blob/main/packages/react-scripts/scripts/utils/createJestConfig.js#L74)