I was mocking an independent class method using the jest.spyOn but instead of mocked implementation, the actual method is called

Viewed 20

Class File

//Consumer class
class Consumer {
constructor(){
}
getConsumerData(){
//does something and does not return anything
}
}

Inside react component button click this method is being called

//ReactComponent.tsx

handleButtonClick() {
Consumer.getConsumerData();
}

Test File

  const methodSpy = jest.spyOn(Consumer.prototype, "getConsumer").mockImplementation(()=>{});
  expect(methodSpy).toHaveBeenCalled();
1 Answers

You can mock the whole Consumer

  1. Make sure Consumer is the default export of its file
import Consumer from './consumer';
///...
jest.mock('./consumer'); // SoundPlayer is now a mock constructor


beforeEach(() => {
  // Clear all instances and calls to the constructor and all methods:
  Consumer.mockClear();
});

/// Your tests

More details: https://jestjs.io/docs/es6-class-mocks

Related