【问题标题】:Click Handle on Jest单击“玩笑处理”
【发布时间】:2018-10-08 07:36:06
【问题描述】:

我正在使用 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()
    });

【问题讨论】:

    标签: reactjs jestjs jest-fetch-mock


    【解决方案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();
    

    希望对你有帮助。

    【讨论】:

    • 嗨,Alex,感谢您的回复,第一个解决方案给出了错误“预期的模拟函数已被调用,但它未被调用”。
    • 是的,点击模拟应该在预期之前
    • 我已经这样做了,但它给出了错误? test('Section', () => { const handleClick = jest.fn(); const wrapper = mount(
      ); wrapper.find('.' + styles.accordionSectionHeading).first().simulate('click'); expect(handleClick).toBeCalled() });
    • 是的,你的代码库没有调用props.handleClick,而是调用了this.handleClick
    • @ShyamKumar 你为什么不检查状态呢?
    猜你喜欢
    • 2016-03-01
    • 2015-12-30
    • 2022-01-13
    • 2021-09-07
    • 2020-10-23
    • 1970-01-01
    • 2020-11-04
    • 2019-05-18
    • 1970-01-01
    相关资源
    最近更新 更多