单击“开玩笑”

时间:2018-10-08 07:36:07

标签: reactjs jestjs jest-fetch-mock

我正在使用笑话来编写测试用例,但如果不是按钮,则无法获得如何测试点击模拟的信息。 如果是按钮,则编写find('button),但是如果单击div并且嵌套了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>
        );
    }
}

这是我开玩笑的测试用例

 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 个答案:

答案 0 :(得分:1)

您可以find element by class

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

此外,您的组件似乎未调用prop handleClick。而是调用实例方法,因此如下所示:

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

似乎更正确。

或者更好的是,您可以只检查状态是否已更改

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

希望有帮助。