react native Unable to find an element with the testID

Viewed 11558

I'm getting this error:

Unable to find an element with the testID of: input-text

Input.js:

import React from "react";
import { View, StyleSheet } from "react-native";
import { Text, TextInput } from "react-native-paper";

const Input = (props) => {
  return (
    <View>
      <TextInput
        name={props.name}
        keyboardType={props.keyboardType}
        value={props.value}
        label={props.label}
        mode="outlined"
        onChange={(newVal) => props.onChange(props.name, newVal)}
        required={props.required}
        data-testid="input-text"
      />
      <Text>{props.errors}</Text>
    </View>
  );
};

export default Input;

Input-test.js:

import React from "react";
import { Input } from "../components/common";

import { render, fireEvent } from "@testing-library/react-native";

import renderer from "react-test-renderer";

const setup = () => {
  const utils = render(<Input />);
  const input = utils.getByTestId("input-text");
  return {
    input,
    ...utils,
  };
};

test("It should display empty value", () => {
  const { input } = setup();
  fireEvent.change(input, { target: { value: "" } });
  expect(input.value).toBe("");
});

The reason I'm using getByTestId is because the input name is dynamic, it is rendered multiple times with using forms, therefore I cannot use anything else.

What am I doing wrong?

Thanks for the help.

2 Answers

I got caught on the same thing. As explained by the error message, testing library is looking for a prop called testID, not data-testid as mentioned in the core documentation. Try changing the prop to testID="input-text" and it should work.

Ciao, according to this guide, to test onChange event in TextInput you have to:

  1. Install react-test-renderer:

    npm i react-test-renderer
    
  2. Modify input component like this:

     const Input = (props) => {
     constructor() {
       super();
       this.state = {
           myVal: ''
       };
     }
    
     handleNewVal = (newVal) => {
        this.setState({myVal: newVal});
     }
    
      return (
      <View>
        <TextInput
          name={props.name}
          keyboardType={props.keyboardType}
          value={props.value}
          label={props.label}
          mode="outlined"
          onChange={(newVal) => this.handleNewVal(newVal)}
          required={props.required}
          data-testid="input-text"
        />
        <Text>{props.errors}</Text>
     </View>
    );
    };
    
  3. Modify your test in this way:

    import renderer from 'react-test-renderer';
    
    test("It should display empty value", () => {
      const instanceOf = renderer.create(<Input />).getInstance();
      instanceOf.handleNewVal('');
      expect(instanceOf.state.myVal).toEqual('');
    });
    
Related