Skip to content

Commit

Permalink
fix(devtools): Do not patch mocked actions (#2300)
Browse files Browse the repository at this point in the history
  • Loading branch information
bodograumann committed Apr 17, 2024
1 parent 938d389 commit 069ffd1
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 12 deletions.
36 changes: 36 additions & 0 deletions 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()
})
})
27 changes: 15 additions & 12 deletions packages/pinia/src/devtools/plugin.ts
Expand Up @@ -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(
Expand Down

0 comments on commit 069ffd1

Please sign in to comment.