Skip to content

Commit 93b5546

Browse files
committed
docs: testing mock store
1 parent 21303de commit 93b5546

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: packages/docs/cookbook/testing.md

+45
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,51 @@ store.someAction()
155155
expect(store.someAction).toHaveBeenCalledTimes(1)
156156
```
157157

158+
### Mocking the returned value of an action
159+
160+
Actions are automatically spied but type-wise, they are still the regular actions. In order to get the correct type, we must implement a custom type-wrapper that is applies the `Mock` type to each action. **This type depends on the testing framework you are using**. Here is an example with Vitest:
161+
162+
```ts
163+
import type { Mock } from 'vitest'
164+
import type { Store, StoreDefinition } from 'pinia'
165+
166+
function mockedStore<TStoreDef extends () => unknown>(
167+
useStore: TStoreDef
168+
): TStoreDef extends StoreDefinition<
169+
infer Id,
170+
infer State,
171+
infer Getters,
172+
infer Actions
173+
>
174+
? Store<
175+
Id,
176+
State,
177+
Getters,
178+
{
179+
[K in keyof Actions]: Actions[K] extends (
180+
...args: infer Args
181+
) => infer ReturnT
182+
? // 👇 depends on your testing framework
183+
Mock<Args, ReturnT>
184+
: Actions[K]
185+
}
186+
>
187+
: ReturnType<TStoreDef> {
188+
return useStore() as any
189+
}
190+
```
191+
192+
This can be used in tests to get a correctly typed store:
193+
194+
```ts
195+
import { mockedStore } from './mockedStore'
196+
import { useSomeStore } from '@/stores/myStore'
197+
198+
const store = mockedStore(useSomeStore)
199+
// typed!
200+
store.someAction.mockResolvedValue('some value')
201+
```
202+
158203
### Specifying the createSpy function
159204

160205
When using Jest, or vitest with `globals: true`, `createTestingPinia` automatically stubs actions using the spy function based on the existing test framework (`jest.fn` or `vitest.fn`). If you are not using `globals: true` or using a different framework, you'll need to provide a [createSpy](/api/interfaces/pinia_testing.TestingOptions.html#createspy) option:

0 commit comments

Comments
 (0)