1 year ago

#382323

test-img

Aessandro

React hook form unit test

I have the following component:

const WorkProviderList: React.FC<StepComponentParams> = ({
  metadata,
}): JSX.Element => {
  const {
    control,
    setValue,
    getValues,
  } = useForm({
    resolver: yupResolver(validationSchema),
    defaultValues: { [CONFIRM_NAME]: true } as any,
    mode: "all",
  });

  ...

  const isOtherFieldNameVisible = getValues()[FIELD_NAME] === "other";

  console.log("isOtherFieldNameVisible: ", isOtherFieldNameVisible);
  return (
    <>
      <Text element="h1" variant="title2Bold">
        Which is your work provider?
      </Text>
      <Text>
        If you work with more than one, select the provider that you work with
        the most.
      </Text>
      <fieldset role="group" aria-labelledby={FIELD_NAME}>
        <Controller
          name={FIELD_NAME}
          control={control}
          render={() => (
            <RadioGroupFields
              fields={radioFields}
              name={FIELD_NAME}
              onChange={(e) => {
                setValue(FIELD_NAME, e.target.value, {
                  shouldValidate: true,
                });
              }}
            />
          )}
        />
      </fieldset>
      {isOtherFieldNameVisible && (
        <div className="py-3">
          <FormField
            name={OTHER_FIELD_NAME}
            label="What is the name of your work provider?"
          >
            <Controller
              name={OTHER_FIELD_NAME}
              control={control}
              render={({ field: { onChange } }) => (
                <TextField
                  id="other_input"
                  isFullWidth
                  name={OTHER_FIELD_NAME}
                  statusType="info"
                  onChange={onChange}
                />
              )}
            />
          </FormField>
        </div>
      )}
    </>
  );
};

and the following test:

const { getByLabelText, getByText } = render(
  <WorkProviderList {...props} />
);
const input = getByLabelText("I work with a different work provider");

fireEvent.change(input, { target: { value: "other" } });
fireEvent.click(input);

const text = getByText("What is the name of your work provider?");
expect(text).toBeInTheDocument();

even though the console.log in the component returns true, I would expect to find the label I am looking for but I get the following error:

TestingLibraryElementError: Unable to find a label with the text of: What is the name of your work provider?

javascript

reactjs

jestjs

react-testing-library

react-hook-form

0 Answers

Your Answer

Accepted video resources