|
| 1 | +import { |
| 2 | + defineForm, |
| 3 | + field, |
| 4 | + privateField, |
| 5 | + formsField, |
| 6 | + toObject, |
| 7 | +} from "../src/index"; |
| 8 | +import * as yup from "yup"; |
| 9 | + |
| 10 | +describe("toObject", () => { |
| 11 | + test("basic form", () => { |
| 12 | + const form = defineForm({ |
| 13 | + a: field("A", yup.string().required()), |
| 14 | + b: field("", yup.string().required()), |
| 15 | + c: field("C", yup.string().required()), |
| 16 | + id: privateField<number | null>(null, yup.number().required()), |
| 17 | + memo: privateField("hello, world"), |
| 18 | + method() {}, |
| 19 | + }); |
| 20 | + expectTypeOf(toObject(form)).toEqualTypeOf<{ |
| 21 | + a: string; |
| 22 | + b: string; |
| 23 | + c: string; |
| 24 | + }>(); |
| 25 | + }); |
| 26 | + |
| 27 | + test("form includes nested forms", () => { |
| 28 | + const form = defineForm({ |
| 29 | + a: { |
| 30 | + a: field("A", yup.string().required()), |
| 31 | + b: { |
| 32 | + a: field("", yup.string().required()), |
| 33 | + }, |
| 34 | + c: field("C", yup.string().required()), |
| 35 | + }, |
| 36 | + b: field("B", yup.string().required()), |
| 37 | + }); |
| 38 | + expectTypeOf(toObject(form)).toEqualTypeOf<{ |
| 39 | + a: { |
| 40 | + a: string; |
| 41 | + b: { |
| 42 | + a: string; |
| 43 | + }; |
| 44 | + c: string; |
| 45 | + }; |
| 46 | + b: string; |
| 47 | + }>(); |
| 48 | + expectTypeOf(toObject(form.a)).toEqualTypeOf<{ |
| 49 | + a: string; |
| 50 | + b: { |
| 51 | + a: string; |
| 52 | + }; |
| 53 | + c: string; |
| 54 | + }>(); |
| 55 | + expectTypeOf(toObject(form.a.b)).toEqualTypeOf<{ |
| 56 | + a: string; |
| 57 | + }>(); |
| 58 | + }); |
| 59 | + |
| 60 | + test("form includes Field<T, U>", () => { |
| 61 | + type Foo = "A" | "B" | "C"; |
| 62 | + |
| 63 | + const form = defineForm({ |
| 64 | + a: field("A", yup.string().required()), |
| 65 | + b: field<Foo | null>("A", yup.string().required()), |
| 66 | + c: field<Foo | null, Foo>("A", yup.string().required()), |
| 67 | + }); |
| 68 | + expectTypeOf(toObject(form)).toEqualTypeOf<{ |
| 69 | + a: string; |
| 70 | + b: Foo | null; |
| 71 | + c: Foo; |
| 72 | + }>(); |
| 73 | + }); |
| 74 | + |
| 75 | + test("form includes formsField", () => { |
| 76 | + const generateSubForm = (initialText = "") => |
| 77 | + defineForm({ |
| 78 | + text: field(initialText, yup.string().required()), |
| 79 | + }); |
| 80 | + |
| 81 | + const form = defineForm({ |
| 82 | + a: formsField(generateSubForm, 1, yup.array().min(1)), |
| 83 | + b: field("B", yup.string().required()), |
| 84 | + }); |
| 85 | + expectTypeOf(toObject(form)).toEqualTypeOf<{ |
| 86 | + a: { text: string }[]; |
| 87 | + b: string; |
| 88 | + }>(); |
| 89 | + expectTypeOf(toObject(form.a.$forms[0]!)).toEqualTypeOf<{ |
| 90 | + text: string; |
| 91 | + }>(); |
| 92 | + }); |
| 93 | +}); |
0 commit comments