我正在使用jest编写一个测试用例,但如果不是按钮,我无法获得如何测试点击模拟。如果是按钮,我们就写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>
);
}
}这是我的jest测试用例
test('Section', () => {
const handleClick = jest.fn();
const wrapper = mount(<Section onClick={ handleClick} title="show more"/>)
wrapper.text('show more').simulate('click')
expect(handleClick).toBeCalled()
});发布于 2018-10-08 17:00:02
wrapper.find('.' + styles.accordionSectionHeading).first().simulate('click')此外,您的组件似乎没有调用prop handleClick。取而代之的是调用实例方法,如下所示:
wrapper.instance().handleClick = jest.fn();
expect(wrapper.instance().handleClick).toBeCalled();看起来更正确。
或者,更好的做法是,您可以只检查状态是否已更改
expect(wrapper.state('open')).toBeTruthy();希望能有所帮助。
https://stackoverflow.com/questions/52697452
复制相似问题