I want to test the event handler in React using Jest / Jasmine / Enzyme.
MyComponent.js
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.clickHandler = this.clickHandler.bind(this);
this.otherMethod = this.otherMethod .bind(this);
}
clickHandler() { this.otherMethod(); }
otherMethod() {}
render() { return <div onClick={this.clickHandler}/>; }
}
export default MyComponent;
MyComponent.test.js
import React from 'react';
import {mount} from 'enzyme';
import MyComponent from './MyComponent';
it('should work', () => {
const componentWrapper = mount(<MyComponent/>);
const component = componentWrapper.get(0);
spyOn(component, 'otherMethod' ).and.callThrough();
spyOn(component, 'clickHandler').and.callThrough();
componentWrapper.find('div').simulate('click');
expect(component.otherMethod ).toHaveBeenCalled(); // works
expect(component.clickHandler).toHaveBeenCalled(); // does not work
});
Despite the fact that I think that I follow the two component methods the same way, one of them (for otherMethod
) works, and the other (for clickHandler
) does not. I explicitly call clickHandler
, because otherMethod
it will not be called if I were not, but toHaveBeenCalled
somehow it is not selected for clickHandler
. Why?
I understand that I do not need to use either .bind(this)
or .and.callThrough()
on otherMethod
, but I use both just to process the two methods the same way and use them on otherMethod
, in fact I should not make any difference.
SO , , . , , . spyOn
, (component
), component
MyComponent
, .
, React (, , reactjs
), - .