From 4e6fa0675b80059635fc7c91fe59bd3a0908f205 Mon Sep 17 00:00:00 2001 From: Miroslav Petrik Date: Mon, 23 Oct 2023 15:52:54 +0200 Subject: [PATCH] fix: sync split hook with field & test use list field actions --- .../list-field/useListFieldActions.test.ts | 65 +++++++++++++++++++ .../list-field/useListFieldActions.ts | 1 - 2 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 src/components/list-field/useListFieldActions.test.ts diff --git a/src/components/list-field/useListFieldActions.test.ts b/src/components/list-field/useListFieldActions.test.ts new file mode 100644 index 0000000..e8557d0 --- /dev/null +++ b/src/components/list-field/useListFieldActions.test.ts @@ -0,0 +1,65 @@ +import { renderHook, act } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; + +import { useListFieldActions } from "./useListFieldActions"; +import { formAtom, useFormSubmit } from "form-atoms"; +import { numberField } from "../../fields"; + +describe("useListFieldActions()", () => { + describe("adding item to the list", () => { + it("submits the new item", async () => { + const form = formAtom({ + luckyNumbers: [numberField({ value: 6 })], + }); + + const builder = () => numberField({ value: 9 }); + + const { result: listFieldAction } = renderHook(() => + useListFieldActions( + form, + builder, + ["luckyNumbers"], + (field) => `${field}` + ) + ); + + const { result: formSubmit } = renderHook(() => useFormSubmit(form)); + + await act(() => listFieldAction.current.add()); + await act(() => listFieldAction.current.add()); + + const onSubmit = vi.fn(); + await act(() => formSubmit.current(onSubmit)()); + + expect(onSubmit).toHaveBeenCalledWith({ luckyNumbers: [6, 9, 9] }); + }); + }); + + describe("removing item from the list", () => { + it("submits without the removed item", async () => { + const form = formAtom({ + luckyNumbers: [numberField({ value: 6 })], + }); + + const builder = () => numberField(); + + const { result: listFieldAction } = renderHook(() => + useListFieldActions( + form, + builder, + ["luckyNumbers"], + (field) => `${field}` + ) + ); + + const { result: formSubmit } = renderHook(() => useFormSubmit(form)); + + await act(() => listFieldAction.current.items[0]?.remove()); + + const onSubmit = vi.fn(); + await act(() => formSubmit.current(onSubmit)()); + + expect(onSubmit).toHaveBeenCalledWith({ luckyNumbers: [] }); + }); + }); +}); diff --git a/src/components/list-field/useListFieldActions.ts b/src/components/list-field/useListFieldActions.ts index 774c588..95db773 100644 --- a/src/components/list-field/useListFieldActions.ts +++ b/src/components/list-field/useListFieldActions.ts @@ -75,7 +75,6 @@ export const useListFieldActions = < } }, fields); - return fields; return { ...fields }; }); }),