timdeschryver / zod-fixture

Creating fixtures based on zod schemas
https://zod-fixture.timdeschryver.dev/
MIT License
122 stars 10 forks source link

Missing ZodOption type #1

Closed kiesman99 closed 2 years ago

kiesman99 commented 2 years ago

Hey there! Thank you very much for your blog articles and of course this awesome library! (Big Fan 😄)

Description

However, i've run into an issue with zod-fixture. I cannot create fixtures of objects containing properties that are optional. It always throws this error message Uncaught Error: Missing type for ZodType "ZodOptional". I think the correct mapping for ZodOptional is missing here.

If I find a solution to this problem, i'll submit a PR. Until then, i just wanted to inform you i've encountered this issue.

Minimal Reproducible

Go to this StackBlitz and open the console of the browser. You'll be greeted with the error message.

Minimal test as reproducible sample

test('creates object with optional value ', () => {
    const SampleWithOptionalValueSchema = z.object({
        name: z.string(),
        modify: z.boolean().optional(),
    });
    expect(() => {console.log(createFixture(SampleWithOptionalValueSchema))}).not.toThrow();
});
timdeschryver commented 2 years ago

Thanks for creating this issue, and including a reproducible snippet 👍

timdeschryver commented 2 years ago

With Optional, the schema type is Optional and this is causing problems at the moment. We have a check for this, but it's at the wrong location. The issue should be resolved after we move this check to a better location.

The fix is to move the check on the inner type at https://github.com/timdeschryver/zod-fixture/blob/main/src/generate.ts#L10-L12 to the extractFromZodSchema method at https://github.com/timdeschryver/zod-fixture/blob/main/src/generate.ts#L27. This way when a property's type is looked up it will use the inner type.

More information:

The "real" type of the property is available on the schema, To get the information of the "real" type we have to dig a bit deeper, and it's available on the schema's definition as _def.innerType.

Feel free to create a PR with a fix if you want.

kiesman99 commented 2 years ago

I will try to look at it the next few days. Thanks for the more detailed description!

github-actions[bot] commented 2 years ago

:tada: This issue has been resolved in version 1.0.1 :tada:

The release is available on:

Your semantic-release bot :package::rocket:

jjmalina commented 2 years ago

@timdeschryver thank you for fixing this! was having the same issue with nullable and it's solved for me now :)

timdeschryver commented 2 years ago

I'm glad to hear that @jjmalina :)