Skip to content

Commit dd30fab

Browse files
committed
docs: mocking getters
1 parent 0a99a75 commit dd30fab

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

packages/docs/cookbook/testing.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Depending on what or how you are testing, we need to take care of these three di
1414
- [Initial State](#initial-state)
1515
- [Customizing behavior of actions](#customizing-behavior-of-actions)
1616
- [Specifying the createSpy function](#specifying-the-createspy-function)
17+
- [Mocking getters](#mocking-getters)
1718
- [E2E tests](#e2e-tests)
1819
- [Unit test components (Vue 2)](#unit-test-components-vue-2)
1920

@@ -175,6 +176,32 @@ createTestingPinia({
175176

176177
You can find more examples in [the tests of the testing package](https://github.com/vuejs/pinia/blob/v2/packages/testing/src/testing.spec.ts).
177178

179+
### Mocking getters
180+
181+
By default, any getter will be computed like regular usage but you can manually force a value by setting the getter to anything you want:
182+
183+
```ts
184+
import { defineStore } from 'pinia'
185+
import { createTestingPinia } from '@pinia/testing'
186+
187+
const useCounter = defineStore('counter', {
188+
state: () => ({ n: 1 }),
189+
getters: {
190+
double: (state) => state.n * 2,
191+
},
192+
})
193+
194+
const pinia = createTestingPinia()
195+
const counter = useCounter(pinia)
196+
197+
counter.double = 3 // 🪄 getters are writable only in tests
198+
199+
// set to undefined to reset the default behavior
200+
// @ts-expect-error: usually it's a number
201+
counter.double = undefined
202+
counter.double // 2 (=1 x 2)
203+
```
204+
178205
## E2E tests
179206

180207
When it comes to pinia, you don't need to change anything for e2e tests, that's the whole point of e2e tests! You could maybe test HTTP requests, but that's way beyond the scope of this guide 😄.

0 commit comments

Comments
 (0)