首页 > 解决方案 > How do I test how a mobile app gets foregrounded?

问题描述

I've got a create-react-native-app and I need to write a test to prevent a regression of an issue when users bring the app back to the foreground (it seems to have difficulty reconnecting the socket.io connection).

Currently I have to manually test this by following some steps:

  1. Open the app
  2. Log in
  3. Wait for login to complete
  4. Switch to another app (background it)
  5. Wait for backgrounded app to lose its server connection (~20 seconds)
  6. Re-open app (foreground it)
  7. Check if issue occurs

How do I go about writing automated tests for this? I'm using jest for unit testing within the app.

标签: react-nativetestingautomated-tests

解决方案


基本用法

要查看当前状态,您可以检查 AppState.currentState,它将保持最新状态。但是,当 AppState 通过网桥检索它时,currentState 将在启动时为空。

import React, {Component} from 'react'
import {AppState, Text} from 'react-native'

class AppStateExample extends Component {

  state = {
    appState: AppState.currentState
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
    }
    this.setState({appState: nextAppState});
  }

  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }

}

推荐阅读