模拟点击-酶
Simulate click - enzyme
我在使用 Enzyme 工具测试 React 应用程序时遇到问题。
在我的组件中,我有登录表单,我想测试一下点击按钮后 p 标签是否会用文本填充。
实际上在点击提交之后有发送请求到api(现在不存在),返回关于无法到达端点的错误。
尝试以多种方式对其进行测试,但发现了一件有趣的事情。使用:
it('returns error if endpoint not reachable', () => {
const wrapper = mount(<LoginForm dispatch={dispatch} store={store} />);
wrapper.find('button').simulate('click');
console.log(wrapper.debug());
});
returns HTML 控制台中的代码。但是那里的 p 标签也没有填写。所以我的问题是如何在这里使用模拟功能?
第一次以为是超时导致的。但是使用 setTimeout 给出了相同的结果。
感谢您的帮助!
Enzyme 提供了提交点击事件的能力。如果它不起作用,我很好奇您是否选择了正确的元素。来自文档的示例...
https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/simulate.md#example
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
const { count } = this.state;
return (
<div>
<div className={`clicks-${count}`}>
{count} clicks
</div>
<a href="url" onClick={() => { this.setState({ count: count + 1 }); }}>
Increment
</a>
</div>
);
}
}
const wrapper = shallow(<Foo />);
expect(wrapper.find('.clicks-0').length).to.equal(1);
wrapper.find('a').simulate('click');
expect(wrapper.find('.clicks-1').length).to.equal(1);
所以在您的特定情况下,您提到在单击提交按钮后会进行 API 调用。您需要使用 Sinon 之类的工具来隔离和模拟此行为。
我在使用 Enzyme 工具测试 React 应用程序时遇到问题。
在我的组件中,我有登录表单,我想测试一下点击按钮后 p 标签是否会用文本填充。
实际上在点击提交之后有发送请求到api(现在不存在),返回关于无法到达端点的错误。
尝试以多种方式对其进行测试,但发现了一件有趣的事情。使用:
it('returns error if endpoint not reachable', () => {
const wrapper = mount(<LoginForm dispatch={dispatch} store={store} />);
wrapper.find('button').simulate('click');
console.log(wrapper.debug());
});
returns HTML 控制台中的代码。但是那里的 p 标签也没有填写。所以我的问题是如何在这里使用模拟功能?
第一次以为是超时导致的。但是使用 setTimeout 给出了相同的结果。
感谢您的帮助!
Enzyme 提供了提交点击事件的能力。如果它不起作用,我很好奇您是否选择了正确的元素。来自文档的示例...
https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/simulate.md#example
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
const { count } = this.state;
return (
<div>
<div className={`clicks-${count}`}>
{count} clicks
</div>
<a href="url" onClick={() => { this.setState({ count: count + 1 }); }}>
Increment
</a>
</div>
);
}
}
const wrapper = shallow(<Foo />);
expect(wrapper.find('.clicks-0').length).to.equal(1);
wrapper.find('a').simulate('click');
expect(wrapper.find('.clicks-1').length).to.equal(1);
所以在您的特定情况下,您提到在单击提交按钮后会进行 API 调用。您需要使用 Sinon 之类的工具来隔离和模拟此行为。