I'm trying to test a TextInput by checking its value after entering a string, but it's not working. Any help would be appreciated.
Here's the code:
import React from 'react'
import { TextInput } from 'react-native'
import { fireEvent, render } from "@testing-library/react-native"
test('<TextInput/>, () => {
const { getByTestId } = render( <TextInput testID="input" /> );
const input = getByTestId("input");
fireEvent.changeText(input, "123");
expect(input.value).toBe("123");
})
The test fails with the message:
Expected: "123"
Received: undefined
I'm trying to test a TextInput by checking its value after entering a string, but it's not working. Any help would be appreciated.
Here's the code:
import React from 'react'
import { TextInput } from 'react-native'
import { fireEvent, render } from "@testing-library/react-native"
test('<TextInput/>, () => {
const { getByTestId } = render( <TextInput testID="input" /> );
const input = getByTestId("input");
fireEvent.changeText(input, "123");
expect(input.value).toBe("123");
})
The test fails with the message:
Expected: "123"
Received: undefined
Share
Improve this question
asked Apr 23, 2022 at 0:45
IronManAYaadIronManAYaad
1931 gold badge3 silver badges9 bronze badges
2
- Whats is the point to test an component that is already test by the RN team? I recommend you an approach a little more near to the user, this component (TextInput) IMHO doesnt require an unit test, you may should test the interaction with other components as here says github.com/vanGalilea/react-native-testing/blob/master/… – enzou Commented Apr 23, 2022 at 4:02
- Okay, but if I wanted to then how would I get it done? – IronManAYaad Commented Apr 23, 2022 at 12:25
2 Answers
Reset to default 21I think your example is not working because you are not controlling the input. Try adding a value
and an onChangeText
function. Something like:
function Example() {
const [value, setValue] = useState('')
return <TextInput value={value} onChangeText={setValue} testID="input" />
}
test('Should apply the value when changing text', () => {
const { getByTestId } = render(<Exampler />);
const input = getByTestId('input');
fireEvent.changeText(input, '123');
expect(input.props.value).toBe('123');
});
Also, you need to check input.props.value
instead of input.value
Hope it helps.
I'm going to suggest a few things to assist you to get to the solution,
- Are you sure
TextInput
has a prop calledtestID
? You usegetByTestId
subsequently, which needs adata-testid
value on the element. So please make sure of this first. - You can try finding the element in another way. Probably use
getByPlaceholderText
or similar.
Once you can get the element properly, and after the fireEvent
, the value should certainly be updated, and assertion would succeed.