]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
docs: mocking getters
authorEduardo San Martin Morote <posva13@gmail.com>
Thu, 31 Mar 2022 17:47:18 +0000 (19:47 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Thu, 31 Mar 2022 17:47:18 +0000 (19:47 +0200)
packages/docs/cookbook/testing.md

index 3c565341ac5bc87e666f98e214c2acca5fe637f4..9252b5e8984399e90049843bb518f7b32c26c225 100644 (file)
@@ -14,6 +14,7 @@ Depending on what or how you are testing, we need to take care of these three di
     - [Initial State](#initial-state)
     - [Customizing behavior of actions](#customizing-behavior-of-actions)
     - [Specifying the createSpy function](#specifying-the-createspy-function)
+    - [Mocking getters](#mocking-getters)
   - [E2E tests](#e2e-tests)
   - [Unit test components (Vue 2)](#unit-test-components-vue-2)
 
@@ -175,6 +176,32 @@ createTestingPinia({
 
 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).
 
+### Mocking getters
+
+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:
+
+```ts
+import { defineStore } from 'pinia'
+import { createTestingPinia } from '@pinia/testing'
+
+const useCounter = defineStore('counter', {
+  state: () => ({ n: 1 }),
+  getters: {
+    double: (state) => state.n * 2,
+  },
+})
+
+const pinia = createTestingPinia()
+const counter = useCounter(pinia)
+
+counter.double = 3 // ðŸª„ getters are writable only in tests
+
+// set to undefined to reset the default behavior
+// @ts-expect-error: usually it's a number
+counter.double = undefined
+counter.double // 2 (=1 x 2)
+```
+
 ## E2E tests
 
 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 ðŸ˜„.