繁体   English   中英

如何在React Native中测试异步ComponentDidMount?

[英]How to test a async ComponentDidMount in React Native?

我确实有一个带有async componentDidMount的SplashContainer

export class SplashContainer extends Component {

  async componentDidMount() {
    let token = await AsyncStorage.getItem('@XXX:token')
    if (token !== null) {
      await this.props.setTokenAvalability(true)
      await this.props.getUserDetails()
    }
    await this.props.navToNextScreen()
  }

  render() {
    return <Splash />
  }
}

function mapDispatchToProps(dispatch) {
  return {
    navToNextScreen: () => dispatch(navToNextScreen(...)),
    setTokenAvalability: (status) => dispatch(setTokenAvalability(status)),
    getUserDetails: () => dispatch(getUserDetails()),
  }
}
export default connect(null, mapDispatchToProps)(SplashContainer);

我在这里有两个问题。

1 我想测试setTokenAvalability and getUserDetails是否已调度。 我确实知道如何测试是否没有异步/等待,如下所示。

it('test SplashContainer', () => {
  const store = mockStore({});
  const props = {
    dispatch: store.dispatch
  }
  const tree = renderer.create(
    <SplashContainer {...props}/>
  ).toJSON();
  const expectedAction = [
    ...
  ]
  expect(store.getActions()).toEqual(expectedAction);
});

2 如何存根AsyncStorage.getItem()

谢谢,

好吧,componentDidMount不是一个异步函数,我在这里唯一能做的就是使用componentDidUpdate方法,该方法将为您提供组件的更新。

我认为阅读this.props.navToNextScreen()函数this.props.navToNextScreen()您误解了redux在这里的工作方式。

您可能不需要等待navToNextScreen函数,它应该只发送一个全局事件,并且您的主要组件应该监听商店中的更改以显示/隐藏您的启动屏幕

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM