Given my component and test below, why does my confirmClickHandler
method still get called when I run my test?
Note: I noticed that when I change the method from a fat arrow function to just a regular function, it gets mocked out correctly. What am I missing here?
class CalendarConfirmation extends React.Component {
...
confirmClickHandler = (e) => {
...
}
}
and my test:
import React from 'react';
import {mount} from 'enzyme';
import CalendarConfirmation from '../components/CalendarConfirmation';
describe('Test CalendarConfirmation', () => {
let calendarConfirmation;
calendarConfirmation = mount (<CalendarConfirmation />);
calendarConfirmation.instance().confirmClickHandler = jest.fn();
...
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With