As of Jest 19, you can do this:

describe('<App />', () => {
  it('calls componentDidMount', () => {
    const spy = jest.spyOn(App.prototype, 'componentDidMount');
    const wrapper = mount(<App />);

jest.spyOn returns a mock function with all the normally available methods such as mockClear, mockReset and mockRestore.

Make sure to set up your spy before you mount with enzyme or create with react-test-renderer so that the created instance has a reference to the mocked function being spied on.


This will not work with jest this way as jest.fn only have a parameter for the implementation. But more important, you should not spy on the internals of the object you want to test. You should think of Foo as a black box where you can put some properties in and get some stuff rendered back. Then you realize that there is no need to test that internal functions of Foo, like componentDidMount, get called. The only thing that matters is the output of the black box.

But if you really want do test it anyway:

const spy = jest.fn()
const componentDidMount = Foo.prototype.componentDidMount
Foo.prototype.componentDidMount = function(){

Related Query

More Query from same tag