]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
test: check we can use the store as argument
authorEduardo San Martin Morote <posva13@gmail.com>
Mon, 5 Oct 2020 08:55:41 +0000 (10:55 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Mon, 5 Oct 2020 08:56:09 +0000 (10:56 +0200)
__tests__/getters.spec.ts
src/store.ts

index 3ef37374c8ee892a54df78efb866a69a8f5f91e9..3fce3aa43b44611cb1b0d248670279962122750b 100644 (file)
@@ -1,6 +1,8 @@
 import { createStore, setActiveReq } from '../src'
 
 describe('Getters', () => {
+  jest.useFakeTimers()
+
   const useStore = () => {
     // create a new store
     setActiveReq({})
@@ -8,11 +10,23 @@ describe('Getters', () => {
       id: 'main',
       state: () => ({
         name: 'Eduardo',
+        forCallCheck: 'foo',
+        callCount: 0,
       }),
       getters: {
         upperCaseName() {
           return this.name.toUpperCase()
         },
+        // works for js users but cannot be typed at the same time as `this`
+        // so it will have to be explicitly typed by the user
+        // https://github.com/posva/pinia/issues/249
+        callCheck(state: any) {
+          setImmediate(() => {
+            // avoid getting tracked
+            state.callCount++
+          })
+          return state.forCallCheck
+        },
         doubleName() {
           return this.upperCaseName
         },
@@ -76,4 +90,22 @@ describe('Getters', () => {
     store.name = 'Ed'
     expect(store.composed).toBe('ED: ok')
   })
+
+  it('computes getters correctly', async () => {
+    const store = useStore()
+    expect(store.callCount).toBe(0)
+    expect(store.callCheck).toBe('foo')
+    expect(store.callCount).toBe(0)
+    jest.runAllImmediates()
+    expect(store.callCount).toBe(1)
+    expect(store.callCheck).toBe('foo')
+    jest.runAllImmediates()
+    expect(store.callCount).toBe(1)
+    expect(store.callCheck).toBe('foo')
+    // changing a different value on the store
+    store.name = 'Ed'
+    jest.runAllImmediates()
+    expect(store.callCount).toBe(1)
+    expect(store.callCheck).toBe('foo')
+  })
 })
index a064c770783b56ff89a2261ba2669b997078304b..876c7f7adcffcac1e796c60bb69e2a1052e9c9ba 100644 (file)
@@ -143,6 +143,9 @@ export function buildStore<
   for (const getterName in getters) {
     computedGetters[getterName] = computed(() => {
       setActiveReq(_r)
+      // we could also pass state.value instead of the store as the first
+      // argument but the later is more flexible for JS users while TS users
+      // will like to use `this` to get all correct typings
       // eslint-disable-next-line @typescript-eslint/no-use-before-define
       return getters[getterName].call(store, store)
     }) as StoreWithGetters<G>[typeof getterName]