From 001b79eb7252beb8837ccf788f1fca3e8c6cfc44 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Wed, 12 May 2021 14:19:08 +0200 Subject: [PATCH] test: lifespan with ref --- __tests__/lifespan.spec.ts | 57 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/__tests__/lifespan.spec.ts b/__tests__/lifespan.spec.ts index aef85fb7..1ab83bd5 100644 --- a/__tests__/lifespan.spec.ts +++ b/__tests__/lifespan.spec.ts @@ -1,6 +1,6 @@ -import { createPinia, defineStore } from '../src' +import { createPinia, defineStore, setActivePinia } from '../src' import { mount } from '@vue/test-utils' -import { watch, nextTick, defineComponent } from 'vue' +import { watch, nextTick, defineComponent, ref, Ref } from 'vue' describe('Store Lifespan', () => { function defineMyStore() { @@ -9,6 +9,7 @@ describe('Store Lifespan', () => { state: () => ({ a: true, n: 0, + aRef: ref(0), nested: { foo: 'foo', a: { b: 'string' }, @@ -68,4 +69,56 @@ describe('Store Lifespan', () => { await nextTick() expect(inComponentWatch).toHaveBeenCalledTimes(2) }) + + it('ref in state reactivity outlives component life', async () => { + let n: Ref + const pinia = createPinia() + setActivePinia(pinia) + const globalWatch = jest.fn() + const destroy = watch(() => pinia.state.value.a?.n, globalWatch) + + const useStore = defineStore({ + id: 'a', + state: () => { + n = n || ref(0) + return { n } + }, + }) + + const Component = defineComponent({ + render: () => null, + setup() { + const store = useStore() + store.n++ + }, + }) + + const options = { + global: { + plugins: [pinia], + }, + } + + let wrapper = mount(Component, options) + await wrapper.unmount() + + expect(globalWatch).toHaveBeenCalledTimes(1) + + let store = useStore() + store.n++ + await nextTick() + expect(globalWatch).toHaveBeenCalledTimes(2) + + wrapper = mount(Component, options) + await wrapper.unmount() + + expect(globalWatch).toHaveBeenCalledTimes(3) + + store = useStore() + store.n++ + await nextTick() + expect(globalWatch).toHaveBeenCalledTimes(4) + + destroy() + }) }) -- 2.47.2