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 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,
TextInput has a prop called testID? You use getByTestId subsequently, which needs a data-testid value on the element. So please make sure of this first.getByPlaceholderText or similar.Once you can get the element properly, and after the fireEvent, the value should certainly be updated, and assertion would succeed.