react-native - 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:
- Open the app
- Log in
- Wait for login to complete
- Switch to another app (background it)
- Wait for backgrounded app to lose its server connection (~20 seconds)
- Re-open app (foreground it)
- Check if issue occurs
How do I go about writing automated tests for this? I'm using jest
for unit testing within the app.
解决方案
基本用法
要查看当前状态,您可以检查 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>
);
}
}
推荐阅读
- javascript - 我们可以访问临时存储图像的 chrome 存储吗?
- javascript - 使用前端 javascript 文件中的电子 ipcRenderer
- python - 无法使用 Selenium Python 以表格形式获取数据
- apache-spark - 我们如何管理 Spark Structured Streaming 中的偏移量?( _spark_metadata 的问题)
- snowboy - Snowboy 关闭后构建 umdl/pmdl
- node.js - 无法使用 Node.js 接收 IPv6 UDP 多播消息
- google-apps-script - 使用应用脚本插入谷歌分析过滤器,权限错误
- ms-access - 如何让 MS Access 立即从 PG 后端读取所有数据?
- c# - C# DateTime - 将 DateTimeOffset 转换为另一个 TimeZone
- c - c:与左移相反的操作