SirNoob
SirNoob

Reputation: 669

jest.fn returns undefined when called

I am trying to implement a fetch mock function in my test. Following tutorials I am trying to do this by using jest.fn():

const fetchFunction = jest.fn(() => {
    return null
})

This does not work for some reason. If I just do console.log(fetchFunction) in my test I get:

[Function: mockConstructor] {
        _isMockFunction: true,
        getMockImplementation: [Function],
        mock: [Getter/Setter],
        mockClear: [Function],
        mockReset: [Function],
        mockRestore: [Function],
        mockReturnValueOnce: [Function],
        mockResolvedValueOnce: [Function],
        mockRejectedValueOnce: [Function],
        mockReturnValue: [Function],
        mockResolvedValue: [Function],
        mockRejectedValue: [Function],
        mockImplementationOnce: [Function],
        mockImplementation: [Function],
        mockReturnThis: [Function],
        mockName: [Function],
        getMockName: [Function]
      }

However if I try to invoke it by console.log(fetchFunction()) I get undefined?

I am trying this to do in a create-react-app folder. Do I have to install something extra? Any ideas about why this happens?

Upvotes: 5

Views: 5737

Answers (3)

Yair Nevet
Yair Nevet

Reputation: 13003

if your jest's resetMocks config attribute is set to true, you should expect that behavior according to the docs:

Automatically reset mock state before every test. Equivalent to calling jest.resetAllMocks() before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.

https://jestjs.io/docs/configuration#resetmocks-boolean

With resetMocks set to true, I resolved it by defining my mock function implementation within the test itself:

it('your test' ()=> {
  //define your mock implementation here
})

Upvotes: 2

Tobbe
Tobbe

Reputation: 3824

It's because Create-React-App has resetMocks on by default. To turn it off you can put this in your package.json

"jest": {
  "resetMocks": false
}

They changed this for the 4.0 release. And they did mention it in their changelog https://github.com/facebook/create-react-app/blob/master/CHANGELOG.md#400-2020-10-23 But I'm guessing I'm not alone in missing that/not knowing about that...

There is an open issue about reverting that change: https://github.com/facebook/create-react-app/issues/9935

Upvotes: 12

Dean James
Dean James

Reputation: 2623

Validated that the following works as expected:

test('Some test...', () => {
  const fetchFunction = jest.fn(() => null)

  console.log(fetchFunction());
});

Using Jest 24.9.0.

 PASS  ./test.js
  ✓ foo (31ms)

  console.log test.js:6
    null

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.677s
Ran all test suites

Upvotes: 1

Related Questions