From 069ffd14a52ccb576d63d03d06b18dee69185ae7 Mon Sep 17 00:00:00 2001 From: Bodo Graumann Date: Wed, 17 Apr 2024 10:05:59 +0200 Subject: [PATCH] fix(devtools): Do not patch mocked actions (#2300) --- packages/pinia/__tests__/devtools.spec.ts | 36 +++++++++++++++++++++++ packages/pinia/src/devtools/plugin.ts | 27 +++++++++-------- 2 files changed, 51 insertions(+), 12 deletions(-) create mode 100644 packages/pinia/__tests__/devtools.spec.ts diff --git a/packages/pinia/__tests__/devtools.spec.ts b/packages/pinia/__tests__/devtools.spec.ts new file mode 100644 index 0000000000..5d45692d2f --- /dev/null +++ b/packages/pinia/__tests__/devtools.spec.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from 'vitest' +import { mount } from '@vue/test-utils' +import { createPinia, defineStore } from '../src' +import { devtoolsPlugin } from '../src/devtools' + +describe('devtoolsPlugin', () => { + const useStore = defineStore('test', { + actions: { + myAction() { + return 42 + }, + }, + }) + + it('preserves mocked actions during testing', () => { + const pinia = createPinia() + // Simulate using createTestingPinia + pinia._testing = true + + mount({ template: 'none' }, { global: { plugins: [pinia] } }) + + // Simulate mocking with @pinia/testing createSpy + pinia.use(({ store, options }) => { + Object.keys(options.actions).forEach((action) => { + store[action]._mockImplementation = () => {} + }) + }) + // Previously the mocked actions would be wrapped again + pinia.use(devtoolsPlugin) + + const store = useStore(pinia) + + // @ts-expect-error we have not actually loaded @pinia/testing and mocked actions + expect(store.myAction._mockImplementation).toBeDefined() + }) +}) diff --git a/packages/pinia/src/devtools/plugin.ts b/packages/pinia/src/devtools/plugin.ts index 82d36bd8c2..e122a04d1b 100644 --- a/packages/pinia/src/devtools/plugin.ts +++ b/packages/pinia/src/devtools/plugin.ts @@ -566,21 +566,24 @@ export function devtoolsPlugin< // detect option api vs setup api store._isOptionsAPI = !!options.state - patchActionForGrouping( - store as StoreGeneric, - Object.keys(options.actions), - store._isOptionsAPI - ) - - // Upgrade the HMR to also update the new actions - const originalHotUpdate = store._hotUpdate - toRaw(store)._hotUpdate = function (newStore) { - originalHotUpdate.apply(this, arguments as any) + // Do not overwrite actions mocked by @pinia/testing (#2298) + if (!store._p._testing) { patchActionForGrouping( store as StoreGeneric, - Object.keys(newStore._hmrPayload.actions), - !!store._isOptionsAPI + Object.keys(options.actions), + store._isOptionsAPI ) + + // Upgrade the HMR to also update the new actions + const originalHotUpdate = store._hotUpdate + toRaw(store)._hotUpdate = function (newStore) { + originalHotUpdate.apply(this, arguments as any) + patchActionForGrouping( + store as StoreGeneric, + Object.keys(newStore._hmrPayload.actions), + !!store._isOptionsAPI + ) + } } addStoreToDevtools(