What's the best way to tell TS that getters are writable in unit tests? #2649
-
When writing tests for components, I often have to set the value of some getters (instead of setting the state)
Pinia allows for this (thanks!), but there is no way for TS to know that this property is not read-only in this context. What I end up doing is something along the following lines:
This works fine, but it's a bit cumbersome to write in every single test. Is there a way for Pinia to do this for me? I don't want to touch the production code and add generics to accomplish this, but I think it would be great to have out of the box something like
or even if there is a way to use a different pattern, so I don't have to change anything in the unit tests. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is the code I use: function mockedStore<TStoreDef extends () => unknown>(
useStore: TStoreDef,
): TStoreDef extends StoreDefinition<infer Id, infer State, infer Getters, infer Actions>
? Store<
Id,
State,
Record<string, never>,
{
[K in keyof Actions]: Actions[K] extends (...args: infer Args) => infer ReturnT
? Mock<Args, ReturnT>
: Actions[K]
}
> & {
[K in keyof Getters]: Getters[K] extends ComputedRef<infer T> ? T : never
}
: ReturnType<TStoreDef> {
return useStore() as any
} Usage: const useStore = defineStore('...', () => {})
const store = mockedStore(useStore) I need to add a page for this in the docs, it's one of the topics I cover in depth in Mastering Pinia 😁 |
Beta Was this translation helpful? Give feedback.
This is the code I use:
Usage:
I need to add a page for this in the docs…