I am trying to query a button with a specific text in react native (yes there is another similar question but it didn't work for me). I want to getByRole the 'Login' Button of my screen but it gets my 'Register' Button as well.
it('renders buttons', () => {
const {getByRole} = render(<LoginScreen />);
getByRole('button', {description: 'Login'});
});
This is what i get as error
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 | });
And this is the code :
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'},
});
I also tried queries like
getByText('Login', {selector : 'button'})
and
getByRole('button', {name : 'Login'})
All I want is to get a button with specific text without getting the other button with a different text. But it really feels as if the second argument is getting ignored whatever i do.
Can anyone help me on this ?
The easiest way around this is to assign the button a testID, and then use getByTestId from react-native-testing-library.
// in component
<Button
testID='LoginButton'
...
// in test
const { getByTestId } = render(<LoginScreen />);
expect(getByTestId('LoginButton')).toBeDefined();