Click Handle on Jest

1.6k Views Asked by At

I am writing a test case using jest, but I am not able to get how to test click simulation if it is not button. If it is button we write find('button), but what if we click on div and there are nested div

class Section extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            open: props.open,
            className: 'accordion-content accordion-close',
            headingClassName: 'accordion-heading'
        };

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState({
            open: !this.state.open
        });
    }

    render() {
        const { title, children } = this.props;
        const { open } = this.state;
        const sectionStateClassname = open
            ? styles.accordionSectionContentOpened
            : styles.accordionSectionContentClosed;

        return (
            <div className={styles.accordionSection}>
                <div
                    className={styles.accordionSectionHeading}
                    onClick={this.handleClick}
                    id="123"
                >
                    {title}
                </div>
                <div
                    className={`${
                        styles.accordionSectionContent
                    } ${sectionStateClassname}`}
                >
                    {children}
                </div>
            </div>
        );
    }
}

here is my jest test case

 test('Section', () => {
        const handleClick = jest.fn();
        const wrapper = mount(<Section  onClick={ handleClick} title="show more"/>)
        wrapper.text('show more').simulate('click')
        expect(handleClick).toBeCalled()
    });
1

There are 1 best solutions below

8
On

You can find element by class:

wrapper.find('.' + styles.accordionSectionHeading).first().simulate('click')

Also, your component seems to not call prop handleClick. Instead, instance method is called, so something like this:

wrapper.instance().handleClick = jest.fn();
expect(wrapper.instance().handleClick).toBeCalled();

seems to be more correct.

Or, better, you can just check if state is changed

expect(wrapper.state('open')).toBeTruthy();

Hope it helps.