Skip to content

Commit

Permalink
fix(conform-zod): when should default to true
Browse files Browse the repository at this point in the history
  • Loading branch information
edmundhung committed Jul 10, 2023
1 parent 52aa84f commit 998d98a
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/conform-zod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ export function refine(
path?: z.IssueData['path'];
},
): void | Promise<void> {
if (!options.when) {
if (typeof options.when !== 'undefined' && !options.when) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: VALIDATION_SKIPPED,
Expand Down
76 changes: 76 additions & 0 deletions tests/conform-zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
getFieldsetConstraint,
parse,
ifNonEmptyString,
refine,
} from '@conform-to/zod';
import { z } from 'zod';
import { installGlobals } from '@remix-run/node';
Expand Down Expand Up @@ -267,4 +268,79 @@ test.describe('conform-zod', () => {
},
});
});

test('parse with refine', () => {
const createSchema = (
validate?: (email) => Promise<boolean> | boolean,
when?: boolean,
) =>
z.object({
email: z
.string()
.email()
.superRefine((email, ctx) =>
refine(ctx, {
validate: () => validate?.(email),
when,
message: 'Email is invalid',
}),
),
});
const formData = createFormData([['email', '[email protected]']]);
const submission = {
intent: 'submit',
payload: {
email: '[email protected]',
},
};

expect(parse(formData, { schema: createSchema() })).toEqual({
...submission,
error: {
email: '__undefined__',
},
});
expect(parse(formData, { schema: createSchema(() => false) })).toEqual({
...submission,
error: {
email: 'Email is invalid',
},
});
expect(parse(formData, { schema: createSchema(() => true) })).toEqual({
...submission,
error: {},
value: submission.payload,
});
expect(
parse(formData, { schema: createSchema(() => true, false) }),
).toEqual({
...submission,
error: {
email: '__skipped__',
},
});
expect(
parse(formData, { schema: createSchema(() => false, false) }),
).toEqual({
...submission,
error: {
email: '__skipped__',
},
});
expect(
parse(formData, { schema: createSchema(() => false, true) }),
).toEqual({
...submission,
error: {
email: 'Email is invalid',
},
});
expect(parse(formData, { schema: createSchema(() => true, true) })).toEqual(
{
...submission,
error: {},
value: submission.payload,
},
);
});
});

0 comments on commit 998d98a

Please sign in to comment.