'Jest cannot read property 'instances' of undefined when mocking es6 classes

Trying to mock ES6 class, just to get a dummy mock I can spy on. My code seems to follow the documentation quite closely, but I get this error when calling .mock on my dummy:

TypeError: Cannot read property 'instances' of undefined

jest.mock('../../../adapters/Cache')
const Fizz = require('../Fizz')
const Cache = require('../../../adapters/Cache')

const fizz = new Fizz()

describe('CACHE', () => {
  it('should return a mock', () => {
    //This is the line that fails
    const mockCache = Cache.mock.instances[0]

    const mockRetrieveRecords = mockCache.retrieveRecords
    fizz.doStuff()
    expect(mockRetrieveRecords).toHaveBeenCalledTimes(1)
  })
})


Solution 1:[1]

jest.mock('../../../adapters/Cache') will mock the module with just undefined. To mock a module that returns a class you could create a mock that just returns a function which returns the mocked instance. To set make the retrieveRecords a spy that you can access in the test, you have to mock the module with an empty spy, import it and set the real mock:

jest.mock('../../../adapters/Cache', () => jest.fn())
const Cache = require('../../../adapters/Cache')
const Fizz = require('../Fizz')

const retrieveRecords = jest.fn()
Cache.mockImplementation(() => ({retrieveRecords})



describe('CACHE', () => {
  it('should return a mock', () => {
    const fizz = new Fizz()
    fizz.doStuff()
    expect(retrieveRecords).toHaveBeenCalledTimes(1)
  })
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andreas Köberle