1

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}
   />
1
  • Why don't you use the top priority query of finding the component by role, in which case the specific value of the ID (which is not the same as a test ID) is irrelevant? Commented Dec 27, 2022 at 11:41

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.