reactjs - 模拟点击 React with Enzyme 不做任何事情
问题描述
我有一个 React 组件类,我正在尝试测试点击行为,但对于我的生活,我无法让模拟实际运行。这是组件类:
class Navbar extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<NavbarWrapper expand={this.props.expand}>
<NavbarBrand>{logo}</NavbarBrand>
<NavbarToggler onClick={this.toggle} collapsed={!this.state.isOpen}>
<NavbarIconBar className="top-bar" />
<NavbarIconBar className="middle-bar" />
<NavbarIconBar className="bottom-bar" />
</NavbarToggler>
<NavbarCollapsibleContent isOpen={this.state.isOpen} navbar>
{this.props.children}
</NavbarCollapsibleContent>
</NavbarWrapper>
);
}
}
这是测试:
const wrapper = shallow(<Navbar {...props} />);
const toggler = wrapper.find(NavbarToggler);
const content = wrapper.find(NavbarCollapsibleContent);
// initial state
expect(content.props().isOpen).toBe(false);
// click to expand (i.e. NOT collapse)
toggler.simulate("click");
expect(content.props().isOpen).toBe(true);
// click to collapse
toggler.simulate("click");
expect(content.props().isOpen).toBe(false);
由于组件isOpen
属性的初始状态是false
,所以第一个期望语句运行成功。但是,第二个测试失败,控制台输出:
● Navbar › should toggle 'NavbarCollapsibleContent's 'isOpen' state when clicking on 'NavbarToggler'
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
这似乎暗示模拟不起作用。我在这里做错了什么?
解决方案
该问题是由于引用了const content
在测试顶部创建的现有内容而引起的,该内容在更新后变得陈旧。将测试套件更改为:
const wrapper = shallowTestComponent();
const toggler = wrapper.find(NavbarToggler);
// initial state
expect(wrapper.find(NavbarCollapsibleContent).props().isOpen).toBe(false);
// click to expand (i.e. NOT collapse)
toggler.simulate("click");
expect(wrapper.find(NavbarCollapsibleContent).props().isOpen).toBe(true);
// click to collapse
toggler.simulate("click");
expect(wrapper.find(NavbarCollapsibleContent).props().isOpen).toBe(false);
解决了我的问题。
推荐阅读
- angular - 时间过长时重试连接
- android - Tinting a gradient button background?
- ios - 网络连接丢失 - 错误域 = kCFErrorDomainCFNetwork 代码 = -1005 - 在 GET 响应中
- r - execute multiple scripts (subtract results)
- python - 在熊猫中从列表创建df(最多将第n个数值填入一列然后继续..)
- javascript - 添加新的html内容时如何删除旧的html?
- scala - Spark String column to element array with a case class
- regex - Powershell string -replace 记得第一个参数值吗?
- tensorflow - 恢复模型 tf.estimator.DNNClassifier
- java - 为什么嘲笑私有领域不好?