Skip to content
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

feat(vitest): add return type and promisable mockFactory #6139

Merged
6 changes: 4 additions & 2 deletions packages/vitest/src/types/mocker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
type Promisable<T> = T | Promise<T>

export type MockFactoryWithHelper<M = unknown> = (
importOriginal: <T extends M>() => Promise<T>
) => any
importOriginal: <T extends M = M>() => Promise<T>
) => Promisable<Record<keyof M, any> | null>
Copy link

@acidoxee acidoxee Jul 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My apologies if my initial issue wasn't clear, but what I meant with a "compatible" mock type was not only regarding the keys in the export map, but their values as well.

Ensuring compatible top-level keys would already be a welcome improvement of course, but this doesn't address the correctness of the exports themselves. I'd still be able to provide a completely false (type-wise) mock from the factory, and TypeScript wouldn't tell me anything about it. I would still need to manually add the Awaited<ReturnType<typeof importOriginal>> return type to each of my factories to ensure my mocks are correct.

I reckon being this strict would probably break some people's current types in tests, because they actually have no idea that their mocks are incomplete or plain wrong, but that's the point. I'd understand that some people would want wildly different mocks than their runtime version, even if it breaks their types and the initial module's signature, but in that case they can still escape type validation with a manual any, while the default could be strict adherence to the original module's signature. WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was a change to keep it as compatible as possible. For typescript users, I thought maybe it could be a breaking change.

I think there are advantages to both from different perspectives. If necessary, I will revise it according to the opinions of other users or maintainers.

export type MockFactory = () => any

export type MockMap = Map<string, Record<string, string | null | MockFactory>>
Expand Down
Loading