Skip to content

Commit

Permalink
feat: Add support undefinedable (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
chimame authored Jan 23, 2025
1 parent 2514c54 commit 8288719
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions coercion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ export function enableTypeCoercion<
schema: generateReturnSchema(type, exactOptionalSchema),
};
}
case "undefinedable":
case "optional":
case "nullish":
case "nullable":
Expand Down
27 changes: 27 additions & 0 deletions tests/coercion/schema/undefinedable.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { number, object, string, undefinedable } from "valibot";
import { describe, expect, test } from "vitest";
import { parseWithValibot } from "../../../parse";
import { createFormData } from "../../helpers/FormData";

describe("undefinedable", () => {
test("should pass only undefinedable", () => {
const schema = object({ name: string(), age: undefinedable(number()) });
const formData1 = createFormData("name", "Jane");
formData1.append("age", "");
expect(parseWithValibot(formData1, { schema })).toMatchObject({
status: "success",
value: { name: "Jane", age: undefined },
});

const formData2 = createFormData("name", "Jane");
expect(parseWithValibot(formData2, { schema })).toMatchObject({
error: { age: expect.anything() },
});

formData2.append("age", "20");
expect(parseWithValibot(formData2, { schema })).toMatchObject({
status: "success",
value: { name: "Jane", age: 20 },
});
});
});
30 changes: 30 additions & 0 deletions tests/coercion/schema/undefinedableAsync.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { number, objectAsync, string, undefinedableAsync } from "valibot";
import { describe, expect, test } from "vitest";
import { parseWithValibot } from "../../../parse";
import { createFormData } from "../../helpers/FormData";

describe("undefinedableAsync", () => {
test("should pass only undefinedable", async () => {
const schema = objectAsync({
name: string(),
age: undefinedableAsync(number()),
});
const formData1 = createFormData("name", "Jane");
formData1.append("age", "");
expect(await parseWithValibot(formData1, { schema })).toMatchObject({
status: "success",
value: { name: "Jane", age: undefined },
});

const formData2 = createFormData("name", "Jane");
expect(await parseWithValibot(formData2, { schema })).toMatchObject({
error: { age: expect.anything() },
});

formData2.append("age", "20");
expect(await parseWithValibot(formData2, { schema })).toMatchObject({
status: "success",
value: { name: "Jane", age: 20 },
});
});
});

0 comments on commit 8288719

Please sign in to comment.