Skip to content
This repository has been archived by the owner on Jun 5, 2023. It is now read-only.

Commit

Permalink
test: 给useFieldState增加用例
Browse files Browse the repository at this point in the history
  • Loading branch information
idler8 committed Mar 2, 2023
1 parent 8d0b08f commit 402277d
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions packages/form-react/__tests__/state.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div>
<div role="input">{JSON.stringify(value)}</div>
<div role="error">{JSON.stringify(errResponse)}</div>
<button
role="button"
onClick={() => onChange(value === "Success" ? "Fail" : "Success")}
>
操作
</button>
<button
role="validator"
onClick={() =>
validator().then(
(res) => {
handleValue.value = res;
handleValue.isError = false;
},
(err) => {
handleValue.value = err;
handleValue.isError = true;
}
)
}
>
验证
</button>
</div>
);
}
render(
<Form>
<FieldInput name={["formKey", "fieldKey"]} />
</Form>
);
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);
});

0 comments on commit 402277d

Please sign in to comment.