Jest - mock fat arrow function within React component Jest - mock fat arrow function within React component reactjs reactjs

Jest - mock fat arrow function within React component


This works for me:

import React from 'react'import { mount, shallow } from 'enzyme'class Foo extends React.Component {  // babel transpiles this too Foo.prototype.canMock  protoMethod () {    // will be mocked  }  // this becomes an instance property  instanceMethod = () => {    return 'NOT be mocked'  }  render () {    return (<div>{`${this.protoMethod()} ${this.instanceMethod()}`}</div>)  }}Foo.prototype.protoMethod = jest.fn().mockReturnValue('you shall')it('should be mocked', () => {  const mock = jest.fn().mockReturnValue('be mocked')  const wrapper = mount(<Foo />)  wrapper.instance().instanceMethod = mock  wrapper.update()  expect(mock).toHaveBeenCalled()})

Note however, that this fails when using shallow instead of mount.


You are not missing anything.

Jest can only mock the structure of objects that are present at require time. It does it by reflection (not by analysis), which means that properties that get added by the constructor cannot be mocked. It's important to understand though that a fat-arrow assignment in a class in JS is not a class method; it's a class property holding a reference to a function.

https://github.com/facebook/jest/issues/6065