J. K.
J. K.

Reputation: 41

Jest, mocking ES6 class constructor not working as intended

I have code that I am trying to test with Jest. I have an ES6 class, let's call it ClassA. Within my test file, I am mocking ClassA as follows:

const mockGetCheapestProductAllPages = jest.fn()
const ClassA = require('../src/ClassA/ClassA')
jest.mock('../src/ClassA/ClassA', () => {
  return jest.fn().mockImplementation(() => {
    return { getCheapestProductAllPages: mockGetCheapestProductAllPages }
  })
})

This syntax works just fine for mocking the class. I am able to spy on getCheapestProductAllPages just fine, and mock return values from it, etc. The problem is, I cannot spy on the constructor for some reason. In the Jest documentation on mocking ES6 classes, it is implied that you can just reference the imported class in order to spy on the constructor, like so:

expect(ClassA).toHaveBeenCalled()

Unfortunately, this is not working for me. I know the constructor is being invoked in my test, but Jest tells me it is invoked 0 times. Any suggestions/anything look wrong? Tried to only share relevant code but please let me know if there is anything else you need to see. Thanks!

Upvotes: 1

Views: 2314

Answers (1)

J. K.
J. K.

Reputation: 41

Ended up declaring my Jest mockImplementation outside of my mock and referencing it in my tests like so:

// top of test file
const mockGetCheapestProductAllPages = jest.fn()
const mockClassAImplementation = jest.fn().mockImplementation(() => {
  return { getCheapestProductAllPages: mockGetCheapestProductAllPages }
})
const ClassA = require('../src/ClassA/ClassA')
jest.mock('../src/ClassA/ClassA', () => {
  return mockClassAImplementation
})

// tests
test('Expect ClassA constructor to be called', () => {
  // invoke method that invokes ClassA constructor
  // this works!
  expect(mockClassAImplementation).toHaveBeenCalled()
})

Upvotes: 1

Related Questions