I can not follow the event handler, although I can follow other methods

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 otherMethodit will not be called if I were not, but toHaveBeenCalledsomehow 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 ), - .

+2
1

.

, onClick React, , , "" .

, , , . instance() , , .

const wrapper = mount(<MyComponent />)
const instance = wrapper.instance()
instance.clickHandler()
//assert whatever

, , ( ) .:)

http://airbnb.io/enzyme/docs/api/ReactWrapper/instance.html

, !

+2

Source: https://habr.com/ru/post/1014161/


All Articles