From 93d25f035bd84fe0924b220d28afaeaee2cb5c47 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Mon, 5 Oct 2020 10:55:41 +0200 Subject: [PATCH] test: check we can use the store as argument --- __tests__/getters.spec.ts | 32 ++++++++++++++++++++++++++++++++ src/store.ts | 3 +++ 2 files changed, 35 insertions(+) diff --git a/__tests__/getters.spec.ts b/__tests__/getters.spec.ts index 3ef37374..3fce3aa4 100644 --- a/__tests__/getters.spec.ts +++ b/__tests__/getters.spec.ts @@ -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') + }) }) diff --git a/src/store.ts b/src/store.ts index a064c770..876c7f7a 100644 --- a/src/store.ts +++ b/src/store.ts @@ -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[typeof getterName] -- 2.47.3