reactjs - enzyme 模拟子组件的onChange事件

标签 reactjs jestjs enzyme react-testing-library

我正在使用 enzyme 和 Jest 来测试我的 React 应用程序,现在我尝试在子组件中触发“onChange”。

class MyComponent extends Component {
    
    state = {
        active: null
    };

    handleChange = panel => (event, active) => {
        this.setState({
            active: (active ? tabs : null)
        });
    };

    render() {
        const { colors, tabs } = this.props;
        const { active } = this.state;

        return (
            <div className={colors.black}>
                { panes.map( ( { left, right } , key ) => 
                    <ChildComponent key={key} expanded={active === key} onChange={this.handleChange(key)}>
                        <ChildComponentLeft />}>{left}</ChildComponentLeft>
                        <ChildComponentRight>{right}</ChildComponentRight>
                    </ChildComponent> 
) 
                }
            </div>
        );
    }
}
export default withStyles(styles)(MyComponent);

我如何测试这个“onChange”?

最佳答案

这应该可以解决问题:

wrapper.find('ChildComponent').simulate('change', {
  target: { /* whatever */ },
});

(如果您有多个 ChildComponent,请在 .find() 之后添加 .at() 调用)

确保通过 wrapper.update 强制重新绘制在 change 事件之后确保您的组件得到重新渲染。

关于reactjs - enzyme 模拟子组件的onChange事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63062713/

相关文章:

reactjs - 找不到相对于目录的预设 "airbnb"

reactjs - react 'componentWillReceiveProps' 使用

javascript - import() 相当于 import { some } from 'somewhere' ;

javascript - React/Redux/Immutable.js - 不可变操作(错误 : Actions must be plain objects)

javascript - 如何在 Jest 的 Worker 的默认函数中测试函数?

javascript - 如何使用 Jest 检查对象属性是否匹配?

javascript - 你如何测试 Vue.js mixin 的模板?

javascript - Node typescript 项目中的 Jest 覆盖总是返回空

reactjs - 使用 enzyme 更改 React 功能组件的 Props

javascript - 如何在 Jest 中模拟/监视 useState 钩子(Hook)?