首页 > 解决方案 > 用多个状态渲染反应原生测试快照?

问题描述

componentDidMount我有一个组件在其方法中多次设置状态。例如:

componentDidMount = async () => {
  this.setState({ waiting: true });
  try {
    const data = await this.fetchData();

    this.setState({ data })
  } catch (err) {
  } finally {
    this.setState({ waiting: false });
  }
};

使用类似于以下的渲染方法:

render() {
    if (this.state.waiting) {
      return (
        <View style={{ flex: 1 }}>
          <ActivityIndicator size="large" />
        </View>
      );
    }

    return (
       ... actual view ...
    )
}

我可以运行测试react-native-testing-library

const tree = testing.render(<HomeScreen {...props} />);

然而我只得到等待视图。但是,当我逐步完成测试时,其他渲染被击中。

所以看起来快照测试只是捕获第一个渲染。有没有办法让它给我最终的渲染?

标签: react-nativereact-native-testing-library

解决方案


原来我需要等待微任务。

await testing.flushMicrotasksQueue();

做到了


推荐阅读