Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 72468a8

Browse files
yz89122claude
andcommitted
test: add test for recursive object with check() method
Add test case demonstrating that recursive objects with custom validation checks work correctly after the mergeDefs fix. The test validates both valid cases (unique sibling IDs) and invalid cases (duplicate sibling IDs) in a nested category structure. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent d74da5f commit 72468a8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

packages/zod/src/v4/classic/tests/recursive-types.test.ts

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,68 @@ test("recursion compatibility", () => {
446446
});
447447
});
448448

449+
test("recursive object with .check()", () => {
450+
const Category = z
451+
.object({
452+
id: z.string(),
453+
name: z.string(),
454+
get subcategories() {
455+
return z.array(Category).optional();
456+
},
457+
})
458+
.check((ctx) => {
459+
// Check for duplicate IDs among direct subcategories
460+
if (ctx.value.subcategories) {
461+
const siblingIds = new Set<string>();
462+
ctx.value.subcategories.forEach((sub, index) => {
463+
if (siblingIds.has(sub.id)) {
464+
ctx.issues.push({
465+
code: "custom",
466+
message: `Duplicate sibling ID found: ${sub.id}`,
467+
path: ["subcategories", index, "id"],
468+
input: ctx.value,
469+
});
470+
}
471+
siblingIds.add(sub.id);
472+
});
473+
}
474+
});
475+
476+
// Valid - siblings have unique IDs
477+
const validData = {
478+
id: "electronics",
479+
name: "Electronics",
480+
subcategories: [
481+
{
482+
id: "computers",
483+
name: "Computers",
484+
subcategories: [
485+
{ id: "laptops", name: "Laptops" },
486+
{ id: "desktops", name: "Desktops" },
487+
],
488+
},
489+
{
490+
id: "phones",
491+
name: "Phones",
492+
},
493+
],
494+
};
495+
496+
// Invalid - duplicate sibling IDs
497+
const invalidData = {
498+
id: "electronics",
499+
name: "Electronics",
500+
subcategories: [
501+
{ id: "computers", name: "Computers" },
502+
{ id: "phones", name: "Phones" },
503+
{ id: "computers", name: "Computers Again" }, // Duplicate at index 2
504+
],
505+
};
506+
507+
expect(() => Category.parse(validData)).not.toThrow();
508+
expect(() => Category.parse(invalidData)).toThrow();
509+
});
510+
449511
// biome-ignore lint: sadf
450512
export type RecursiveA = z.ZodUnion<
451513
[

0 commit comments

Comments
 (0)