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

Viewed 2521

I'm having 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'

on 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', () => {
  //...
})

On 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 on jest doc : https://jestjs.io/docs/mock-functions#mocking-partials

I'm using React (CRA) and TypeScript

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

any idea what I'm doing wrong ? :) Thanks !

1 Answers

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/master/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/master/packages/react-scripts/scripts/utils/createJestConfig.js#L74)

Related