読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
予約のフォームは、Server Actions を直接読み込んでいました。テストでは本物の Server Actions を動かせないため、送信の関数を props で受け取れるようにします。
// src/components/ReserveForm.tsx
"use client";
import { useActionState } from "react";
import type { ReserveState } from "@/app/products/[id]/actions";
type ReserveFormProps = {
productId: string;
action: (prev: ReserveState, formData: FormData) => Promise<ReserveState>;
};
export const ReserveForm = ({ productId, action }: ReserveFormProps) => {
const [state, formAction, isPending] = useActionState(action, {});
// 入力欄と FormField(『状態とデータ フォームの状態と検証』と同じ)
};
// ページでは、本物の Server Actions を渡す
<ReserveForm productId={product.id} action={reserveProduct} />
テストでは、決まった結果を返す関数を渡します。
it("名前のまちがいが、名前の欄のそばに表示される", async () => {
const user = userEvent.setup();
const action = vi.fn(async () => ({
fieldErrors: { name: ["お名前を入力してください"] },
}));
render(<ReserveForm productId="p002" action={action} />);
await user.click(screen.getByRole("button", { name: "予約する" }));
const nameInput = await screen.findByLabelText("お名前");
expect(nameInput.getAttribute("aria-invalid")).toBe("true");
expect(await screen.findByText("お名前を入力してください")).toBeDefined();
expect(action).toHaveBeenCalledTimes(1);
});
| 書き方 | すること |
|---|---|
vi.fn(async () => ...) | 呼ばれた回数と引数を記録する、偽物の関数を作る |
toHaveBeenCalledTimes(1) | 1回だけ呼ばれたことを確かめる |
ここで偽物にしているのは、サーバーとの通信の部分だけです。フォームの表示とまちがいの出し方は、本物の部品で確かめています。サーバーで値を確かめる処理は、スキーマの単体テストで確かめました。
11 / 17