Is it possible to assert if a function is an empty function in jest?
I have a generic input component like this:
class GenericInputComponent extends React.Component {
constructor (props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange (evt) {
this.props.onChange(evt);
}
render () {
return (<Something />)
}
}
GenericComponent.defaultProps = {
onChange: () => {}
}
For this component one of my tests is testing if component is using the default props:
it('should use default props', function () {
delete props.onChange // Before this the onChange was jest.fn()
rendered.unmount()
rendered = shallow(<Input {...props} />)
let onChange = () => {}
expect(rendered.instance().props.onChange).toEqual(onChange)
expect(rendered.instance().props.onChange).toBeInstanceOf(Function)
})
The test fails on the following line:
expect(rendered.instance().props.onChange).toEqual(onChange)
and gives this error:
Expected value to equal:
[Function onChange]
Received:
[Function onChange]
Difference:
Compared values have no visual difference.
From what I see it should be passing but it is not. Why? And is it possible to assert if the function that's being used is an empty function?
Moreover, if I try to spy on the function like this:
let onChangeSpy = jest.spyOn(rendered.instance().props, 'onChange')
I get this error:
`TypeError: Cannot assign to read only property 'onChange' of object '[object Object]'`
FYI, I am using shallow
rendering for the test.
So is it possible to assert on an empty function? Also, this is the only thing keeping coverage
from having a 100% coverage unfortunately.
This is expected because a function is an object, and objects are compared by references in JavaScript:
(() => {}) !== (() => {})
The method could be tested if it's empty by asserting onChange.toString()
. But what should be tested here is that onChange
is not just some empty function but a prop that was set by default. I.e. it should be:
expect(rendered.instance().props.onChange).toBe(GenericInputComponent.defaultProps.onChange)
The function can be optionally tested if it's empty:
expect(GenericInputComponent.defaultProps.onChange).toBeInstanceOf(Function);
expect(GenericInputComponent.defaultProps.onChange.toString().match(/\{(.*)}$/)[1])).toMatch(/^\s*$/);