import { Nullable } from "@reins/types"; import { z } from "zod"; import { FormAdapter } from "../form-adapter"; type InitialValues = { name: string | null; surname: string | null; age: number | null; address: Nullable<{ street: string; city: string; country: string; }>; }; const initialValues: InitialValues = { name: null, surname: null, age: null, address: null, }; describe("Form Adapter [ Validation ]", () => { let form = new FormAdapter(initialValues); beforeEach(() => { form = new FormAdapter(initialValues); }); it("should allow to register validators and validate", async () => { form.registerFieldValidation("address", { validate: z.object({ street: z.string(), city: z.string(), country: z.string(), }), }); const { isValid, firstError, result, values } = await form.validate(); expect(isValid).toBeFalsy(); expect(firstError).toEqual({ field: "address", result: { errors: { validate: "Expected object, received null", }, message: "Expected object, received null", type: "validate", valid: false, }, }); expect(result).toEqual([ { field: "address", result: { errors: { validate: "Expected object, received null", }, message: "Expected object, received null", type: "validate", valid: false, }, }, ]); expect(values).toEqual(initialValues); }); it("should allow to register validators and pass validation", async () => { form.registerFieldValidation("address", { validate: z.object({ street: z.string(), city: z.string(), country: z.string(), }), }); form.setFieldValue("address", { street: "New street", city: "New city", country: "New country", }); const { isValid, firstError, result, values } = await form.validate(); expect(isValid).toBeTruthy(); expect(firstError).toEqual(null); expect(result).toEqual([ { field: "address", result: { errors: { validate: false, }, message: "", type: "none", valid: true, }, }, ]); expect(values).toEqual({ ...initialValues, address: { street: "New street", city: "New city", country: "New country", }, }); }); });