From 1cf5687a80e34e3b385949ff3067d36d5bfb4e62 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Mon, 3 Nov 2025 17:43:10 +0100 Subject: [PATCH] test: unstub specific action See https://github.com/vuejs/pinia/pull/2960 --- packages/testing/src/mocked-store.spec.ts | 104 ++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 packages/testing/src/mocked-store.spec.ts diff --git a/packages/testing/src/mocked-store.spec.ts b/packages/testing/src/mocked-store.spec.ts new file mode 100644 index 00000000..c00ebf77 --- /dev/null +++ b/packages/testing/src/mocked-store.spec.ts @@ -0,0 +1,104 @@ +import { describe, expect, it, vi, type Mock } from 'vitest' +import { computed, defineComponent, ref, type UnwrapRef } from 'vue' +import { defineStore, type Store, type StoreDefinition } from 'pinia' +import { TestingOptions, createTestingPinia } from './testing' +import { mount } from '@vue/test-utils' + +function mockedStore unknown>( + useStore: TStoreDef +): TStoreDef extends StoreDefinition< + infer Id, + infer State, + infer Getters, + infer Actions +> + ? Store< + Id, + State, + Record, + { + [K in keyof Actions]: Actions[K] extends (...args: any[]) => any + ? // 👇 depends on your testing framework + Mock + : Actions[K] + } + > & { + [K in keyof Getters]: UnwrapRef + } + : ReturnType { + return useStore() as any +} + +describe('mockedStore', () => { + const useCounter = defineStore('counter-setup', () => { + const n = ref(0) + const doubleComputedCallCount = ref(0) + const double = computed(() => { + doubleComputedCallCount.value++ + return n.value * 2 + }) + const doublePlusOne = computed(() => double.value + 1) + function increment(amount = 1) { + n.value += amount + } + function decrement() { + n.value-- + } + function setValue(newValue: number) { + n.value = newValue + } + function $reset() { + n.value = 0 + } + + return { + n, + doubleComputedCallCount, + double, + doublePlusOne, + increment, + decrement, + setValue, + $reset, + } + }) + + const Counter = defineComponent({ + setup() { + const counter = useCounter() + return { counter } + }, + template: ` + + {{ counter.n }} + + `, + }) + + function factory(options?: TestingOptions) { + const wrapper = mount(Counter, { + global: { + plugins: [createTestingPinia(options)], + }, + }) + + const counter = mockedStore(useCounter) + + return { wrapper, counter } + } + + it('can unstub actions', () => { + const { counter } = factory({ + stubActions: false, + createSpy: (fn) => vi.fn(fn).mockImplementation(() => {}), + }) + counter.increment() + expect(counter.increment).toHaveBeenCalledTimes(1) + expect(counter.n).toBe(0) + + counter.increment.mockRestore() + counter.increment() + expect(counter.increment).toHaveBeenCalledTimes(1) + expect(counter.n).toBe(1) + }) +}) -- 2.47.3