我正在尝试在 native react 中查询带有特定文本的按钮(是的,还有另一个类似的问题,但它对我不起作用)。我想获取屏幕上的“登录”按钮,但它也获取我的“注册”按钮。
it('renders buttons', () => {
const {getByRole} = render(<LoginScreen />);
getByRole('button', {description: 'Login'});
});
这就是我得到的错误
renders buttons
Expected 1 but found 2 instances with accessibilityRole "button"
11 | it('renders buttons', () => {
12 | const {getByRole} = render(<LoginScreen />);
> 13 | getByRole('button', {description: 'Login'});
| ^
14 | });
这是代码:
import React, {useState} from 'react';
import {SafeAreaView, View, StyleSheet} from 'react-native';
import {Card, TextInput, Button} from 'react-native-paper';
const axios = require('axios').default;
export const LoginScreen = props => {
const [username, setUsername] = useState();
const [password, setPassword] = useState();
const register = () => props.navigation.navigate('Register');
const home = () => props.navigation.navigate('Home');
return (
<SafeAreaView>
<View>
<Card>
<Card.Title title="Login" />
<Card.Content>
<TextInput
accessibilityLabel="Username"
placeholder="example"
onChangeText={txt => setUsername(txt)}
defaultValue={username}
/>
<TextInput
accessibilityLabel="Password"
placeholder="***"
onChangeText={txt => setPassword(txt)}
/>
</Card.Content>
<Card.Actions style={style.button}>
<Button
onPress={() => {
axios({
method: 'post',
url: 'http://10.0.2.2:8000/login',
data: {username: username, password: password},
})
.then(response => {
console.log('0', response);
home();
})
.catch(error => {
console.log('1', error);
});
}}>
Login
</Button>
<Button onPress={register}>Register</Button>
</Card.Actions>
</Card>
</View>
</SafeAreaView>
);
};
const style = StyleSheet.create({
button: {flexDirection: 'row', justifyContent: 'flex-end'},
});
我也尝试过类似的查询
getByText('登录', {selector : '按钮'})
和
getByRole('button', {name : 'Login'})
我想要的只是获得一个具有特定文本的按钮,而不需要获得另一个具有不同文本的按钮。但无论我做什么,都感觉好像第二个参数被忽略了。
谁能帮我解决这个问题吗?
最佳答案
解决这个问题的最简单方法是为按钮分配一个 testID,然后使用react-native-testing-library 中的 getByTestId。
// in component
<Button
testID='LoginButton'
...
// in test
const { getByTestId } = render(<LoginScreen />);
expect(getByTestId('LoginButton')).toBeDefined();
关于javascript - 如何使用 react native 测试库查询具有特定文本的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72183775/