From 402277dd8cb00a091e852334d4d414d93bd6a6c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=B2=E4=BA=BA?= Date: Thu, 2 Mar 2023 10:28:51 +0800 Subject: [PATCH] =?UTF-8?q?test:=20=E7=BB=99useFieldState=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/form-react/__tests__/state.tsx | 80 +++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 packages/form-react/__tests__/state.tsx diff --git a/packages/form-react/__tests__/state.tsx b/packages/form-react/__tests__/state.tsx new file mode 100644 index 0000000..782af4e --- /dev/null +++ b/packages/form-react/__tests__/state.tsx @@ -0,0 +1,80 @@ +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import "@testing-library/jest-dom"; +import { + Form, + useObserver, + FKeys, + useKeys, + useFieldReader, + useFieldTrigger, + useFieldState, + useFormValidator, +} from "index"; +import { useEffect } from "react"; +import type { Keys } from "index"; +import type { Observer } from "@idler8/observer"; + +test("useFieldState", async () => { + function isSuccess(values, keys) { + if (keys?.reduce((prev, key) => prev?.[key], values) !== "Success") { + return `${keys.join(".")} not Success`; + } + } + const handleValue = { value: null, isError: false }; + function FieldInput({ name }) { + const [value, onChange, errResponse] = useFieldState(name, isSuccess); + const validator = useFormValidator(); + return ( +
+
{JSON.stringify(value)}
+
{JSON.stringify(errResponse)}
+ + +
+ ); + } + render( +
+ + + ); + await screen.findByRole("button"); + await userEvent.click(screen.getByRole("button")); + await userEvent.click(screen.getByRole("validator")); + expect(screen.getByRole("input")).toHaveTextContent( + JSON.stringify("Success") + ); + expect(screen.getByRole("error")).toHaveTextContent(""); + expect(handleValue.value).toEqual({ formKey: { fieldKey: "Success" } }); + expect(handleValue.isError).toBe(false); + await userEvent.click(screen.getByRole("button")); + await userEvent.click(screen.getByRole("validator")); + expect(screen.getByRole("input")).toHaveTextContent(JSON.stringify("Fail")); + expect(screen.getByRole("error")).toHaveTextContent( + JSON.stringify("formKey.fieldKey not Success") + ); + expect(handleValue.value).toEqual(["formKey.fieldKey not Success"]); + expect(handleValue.isError).toBe(true); +});