jest.fn returns undefined when called

Viewed 2560

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?

3 Answers

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

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
})
Related