Skip to content

[zod-mock] Fix parseString #217

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/zod-mock/src/lib/zod-mock.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,22 @@ describe('zod-mock', () => {
return;
});

it('Should manually mock string key names to set values when the validation has regex', () => {
const schema = z.object({
telephone: z.string().regex(/^\+[1-9]\d{1,14}$/)
});

const stringMap = {
telephone: () => '+919367788755',
};

const mockData = generateMock(schema, { stringMap });

expect(mockData.telephone).toEqual('+919367788755');

return;
});

it('should convert values produced by Faker to string when the schema type is string.', () => {
const schema = z.object({
number: z.string(),
Expand Down
17 changes: 9 additions & 8 deletions packages/zod-mock/src/lib/zod-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,15 @@ function parseString(
zodRef: z.ZodString,
options?: GenerateMockOptions
): string | number | boolean {
// Prioritize user provided generators.
if (options?.keyName && options.stringMap) {
// min/max length handling is not applied here
const generator = options.stringMap[options.keyName];
if (generator) {
return generator();
}
}

const fakerInstance = options?.faker || faker;
const { checks = [] } = zodRef._def;

Expand All @@ -142,14 +151,6 @@ function parseString(
}

const lowerCaseKeyName = options?.keyName?.toLowerCase();
// Prioritize user provided generators.
if (options?.keyName && options.stringMap) {
// min/max length handling is not applied here
const generator = options.stringMap[options.keyName];
if (generator) {
return generator();
}
}
const stringOptions: {
min?: number;
max?: number;
Expand Down
Loading