[英]How to test React async container components?
On this video: Egghead lecture , Dan Abramov explains and gives a definition of container components. 在此视频: Egghead讲座中 ,Dan Abramov进行了解释并给出了容器组件的定义。 I really liked the idea of container components, but i'm trying to test them, when the container component does not have an async work the test is fine i just simulate some event on the component with Enzyme and then i check the resulting snapshot, but consider the following case when the component has asyn work:
我真的很喜欢容器组件的想法,但是我正在尝试对其进行测试,当容器组件没有异步工作时,测试就很好了,我只是用酶在组件上模拟了一些事件,然后检查生成的快照,但是当组件具有异步工作时,请考虑以下情况:
class Form extends React.Component {
constructor(props){
super(props);
this.state = {};
this.sendForm = props.sendForm;
this.onSubmit = this.onSubmit.bind(this);
this.nameChange = this.nameChange.bind(this);
}
nameChange(e){
this.setState({
name: e.target.value
});
}
onSubmit(e){
e.preventDefault();
this.sendForm({name: this.state.name});
}
return (
<form onSubmit={this.onSubmit}>
<input onChange={this.nameChange} />
</form>
);
}
class Registration extends React.Component {
constructor(props){
super(props);
this.state = {};
this.sendForm = this.sendForm.bind(this);
}
sendForm(data){
fetch(`sendsomewhere.com/?name=${data}`, headers)
.then((result) => this.setState({
result: result
}));
}
render(){
<Form sendForm={this.sendForm} />
}
}
How do i know when the component worked correctly? 我怎么知道组件何时正常工作?
And this question is also for the case where the component does not have an asyn work: How do i know that Registration actually used the fetch function correctly? 这个问题也适用于组件没有异步工作的情况:我怎么知道Registration实际上正确使用了fetch函数? Since it controls itself and there is nothing being injected on the component?
既然它可以控制自身,并且组件上没有注入任何东西?
maybe try returning like 也许尝试像
sendForm(data){
return fetch(`sendsomewhere.com/?name=${data}`, headers)
.then((result) => this.setState({
return result
}));
}
then because result
should be what that returns, you can do something like formResponse = sendForm(data)
then formResponse.status
for a 200 or something. 然后,因为
result
应该是返回的结果,所以您可以执行诸如formResponse = sendForm(data)
然后formResponse.status
formResponse = sendForm(data)
formResponse.status
200)。 This is loosely coded, and untested...something in the syntax may be off, but it's just to give a general idea of how you might get something to test against. 这是松散编码的,未经测试...语法中的某些内容可能已关闭,但这只是为了让您大致了解如何进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.