0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React Testing LibraryでFormの入力値のテストをする

Posted at

React Testing LibraryでFormの入力値が正しいかテストする方法です。

toHaveFormValuesを使用するとinputの値を取得することができました。
toBetoHaveValueで値が取得できると思っていましたができなかったので備忘録です。

src/components/Sample.tsx
"use client";

import { useForm, SubmitHandler } from "react-hook-form";

type SampleForm = {
  sampleName: string;
};

const Sample = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<SampleForm>({
    defaultValues: {
      sampleName: "sampleValue",
    },
  });

  const onSubmit = (data: SampleForm) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} data-testid="test-form">
      <input type="text" {...register("sampleName")} />;
    </form>
  );
};

export default Sample;
src/omponents/test/Sample.test.tsx
import Sample from "@/components/Sample";
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";

describe("Sample", () => {
  it("textbox", () => {
    render(<Sample />);
    expect(screen.getByTestId("test-form")).toHaveFormValues({
      sampleName: "sampleValue",
    });
  });
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?