From: Blake Newman Date: Thu, 31 Mar 2022 09:52:32 +0000 (+0100) Subject: fix(testing): Vue 2 initial state reactive (#1165) X-Git-Tag: @pinia/testing@0.0.11~12 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f23af8eac97b055e58908eb76aae684fd68685b5;p=thirdparty%2Fvuejs%2Fpinia.git fix(testing): Vue 2 initial state reactive (#1165) --- diff --git a/packages/testing/src/testing.ts b/packages/testing/src/testing.ts index 2317d481..cef0bb33 100644 --- a/packages/testing/src/testing.ts +++ b/packages/testing/src/testing.ts @@ -1,10 +1,11 @@ -import { App, createApp } from 'vue-demi' +import { App, createApp, isReactive, isRef, isVue2, set } from 'vue-demi' import { Pinia, PiniaPlugin, setActivePinia, createPinia, StateTree, + _DeepPartial, } from 'pinia' export interface TestingOptions { @@ -89,7 +90,7 @@ export function createTestingPinia({ pinia.use(({ store }) => { if (initialState[store.$id]) { - store.$patch(initialState[store.$id]) + mergeReactiveObjects(store.$state, initialState[store.$id]) } }) @@ -131,3 +132,44 @@ export function createTestingPinia({ return pinia as TestingPinia } + +function mergeReactiveObjects( + target: T, + patchToApply: _DeepPartial +): T { + // no need to go through symbols because they cannot be serialized anyway + for (const key in patchToApply) { + const subPatch = patchToApply[key] + const targetValue = target[key] + if ( + isPlainObject(targetValue) && + isPlainObject(subPatch) && + !isRef(subPatch) && + !isReactive(subPatch) + ) { + target[key] = mergeReactiveObjects(targetValue, subPatch) + } else { + if (isVue2) { + set(target, key, subPatch) + } else { + // @ts-expect-error: subPatch is a valid value + target[key] = subPatch + } + } + } + + return target +} + +function isPlainObject(value: S | unknown): value is S +function isPlainObject( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + o: any +): o is StateTree { + return ( + o && + typeof o === 'object' && + Object.prototype.toString.call(o) === '[object Object]' && + typeof o.toJSON !== 'function' + ) +}