【问题标题】:How to test React async container components?如何测试 React 异步容器组件?
【发布时间】:2018-01-16 23:19:57
【问题描述】:

在此视频中:Egghead lecture,Dan Abramov 解释并给出了容器组件的定义。我真的很喜欢容器组件的想法,但我正在尝试测试它们,当容器组件没有异步工作时,测试很好我只是用酶模拟组件上的一些事件,然后我检查生成的快照,但是当组件具有异步工作时,请考虑以下情况:

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} />
    }
}

我如何知道组件何时正常工作?

这个问题也适用于组件没有异步工作的情况:我怎么知道注册实际上正确使用了 fetch 函数?既然是自己控制的,组件上没有注入任何东西?

【问题讨论】:

  • 可能会返回 fetch,然后您可以记录或检查该函数返回的内容。 return fetch(...) 并返回 result 您可以检查状态代码或其他内容。

标签: reactjs unit-testing asynchronous


【解决方案1】:

也许尝试像这样返回

sendForm(data){
    return fetch(`sendsomewhere.com/?name=${data}`, headers)
           .then((result) => this.setState({
              return result
           }));
}

然后因为result 应该是返回的内容,您可以执行类似formResponse = sendForm(data) 然后formResponse.status 200 之类的操作。这是松散的编码,未经测试......语法中的某些内容可能不正确,但这只是为了让您大致了解如何获得要测试的内容。

【讨论】:

  • 非常感谢您的回答,但我正在考虑通过使用 Enzyme 模拟点击事件来测试 sendForm。另一个问题是如果我做出反应保证:酶(形式).find('#submit-btn').simulate('click',mockObject); registration.componentDidMount = () => {};由于我的模拟事件,我可以确定下一个 componentDidMount 调用将完成吗?
  • 如果我对您的理解正确,您想在单击按钮时安装另一个组件。如果是这样,那么 - 假设原始表单的提交和发送没有任何问题,那么是的。它应该可靠地安装。但是,如果提交/发送表单有错误,则很有可能(取决于它的编码方式和错误处理方式)它不会。
  • React 批量更新,所以如果有五个挂载等待完成,react 将完成所有这些,然后调用 componentDidMount?之前不是很清楚,抱歉。
猜你喜欢
  • 1970-01-01
  • 2019-10-30
  • 2018-10-23
  • 1970-01-01
  • 2018-03-24
  • 2018-11-12
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多