Home > database >  React Testing library with testIdAttribute
React Testing library with testIdAttribute

Time:12-28

I have a Form with children components for input fields, i want to make a test for this input component with the id. The ID is created with useId if it isn't provided so it is dynamically. How can this be done?

test("Input Test", () => {
  const Wrapper = (props: { children: React.ReactNode }) => {
    const formMethods = useForm();
    return <FormProvider {...formMethods}>{props.children}</FormProvider>;
  };

  render(
    <Wrapper>
      <InputField name={"First Name"} label={"fname"} type={"text"} />
      <InputField name={"Last Name"} label={"lname"} type={"text"} />
    </Wrapper>
  );
  configure({ testIdAttribute: "id" });

  const inputfname = screen.getByTestId("fname");
  const inputlname = screen.getByTestId("lname");

  expect(inputfname).toBeInTheDocument();
  expect(inputlname).toBeInTheDocument();

});
  const fieldId = id ?? useId();

  <label htmlFor={fieldId}>{label}</label>
  <input
     id={fieldId}
     {...props}
   />

CodePudding user response:

If you want to test with test-id you have to write your html element like this:

<div data-testid="custom-id" />

You can check the docs here.

And because useId() is a random thing so you can't test it because you don't know the value, so it's better to test your component with another thing.

  • Related