RN 中最基本的 component 例如 View 和 TextInput 都有一个 prop 叫 testID -> 这里是官网说明。
可以用来做 end-to-end test 的 locator。那么它应该显示在哪里呢?根据 facebook 的 code,看起来应该是作为 content description 出现:
ReactTestHelper.java
/**
* Gets the view with a given react test ID in the UI hierarchy. React test ID is currently
* propagated into view content description.
*/
public static View getViewWithReactTestId(View rootView, String testId) {
return findChild(rootView, hasTagValue(testId));
}
于是在 demo 中某个 render 加了类似如下 testID:
render: function() {
return (
<View style = {styles.container}>
...
<View style = {styles.input}>
<TextInput
...
placeholder = {'Your Account'}
testID = 'debug-signin-username-input' />
</View>
<View style = {styles.input}>
<TextInput
...
placeholder = {'Your Password'}
testID = 'debug-signin-passwd-input' />
</View>
...
</View>
);
},
build 好后用 uiautomator 一看,content-desc 是空的:
网上搜了搜发现这个帖子,原文-> React Native put testID into the tag of view, and accessibilityLabel into content description。accessibilityLabel 这个 prop 目前 View 才有,于是改成以下:
render: function() {
return (
<View style = {styles.container}>
...
<View
style = {styles.input}
accessibilityLabel = 'username-input'>
<TextInput
...
placeholder = {'Your Account'} />
</View>
<View
style = {styles.input}
accessibilityLabel = 'passwd-input'>
<TextInput
...
placeholder = {'Your Password'} />
</View>
<TouchableNativeFeedback>
<View style={styles.submit}
accessibilityLabel = 'signin-submit'>
<Text style={styles.submitText}>
SIGN IN
</Text>
</View>
</TouchableNativeFeedback>
</View>
);
},
再用 uiautomator 看,content-desc 有了:
测试代码如下:
def test_find_elements(self):
sleep(5)
user_input = self.driver.find_element_by_accessibility_id("username-input")
user_input.click()
user_input.send_keys('test_account')
pwd_input = self.driver.find_element_by_accessibility_id("passwd-input")
pwd_input.click()
pwd_input.send_keys('123456')
signin_submit = self.driver.find_element_by_accessibility_id("signin-submit")
signin_submit.click()
启动 Appium 跑测试代码,通过。