2

我正在使用 jest 编写一个测试用例,但如果它不是按钮,我无法获得如何测试点击模拟。如果是button我们写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()
    });
4

1 回答 1

1

您可以按类查找元素

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

此外,您的组件似乎没有调用 prop handleClick。相反,实例方法被调用,所以是这样的:

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

似乎更正确。

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

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

希望能帮助到你。

于 2018-10-08T09:00:02.227 回答