import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { getActivePinia, type Store } from 'pinia' import { useResetStore } from '../use-reset-store' import { LIST_STORE_EXCLUDE_RESET } from '#lib/constants' import { useNuxtApp } from 'nuxt/app' // Mock dependencies const mockPiniaInstance = { _s: new Map(), } vi.mock('pinia', () => ({ getActivePinia: vi.fn(), })) vi.mock('#lib/utils', () => ({ removeIsLogged: vi.fn(), })) vi.mock('nuxt/app', () => ({ useNuxtApp: vi.fn().mockReturnValue({ $appCookies: vi.mocked({ getTokenCookie: vi.fn(), setTokenCookie: vi.fn(), token: { value: 'token' } }), }), })) describe('useResetStore', () => { let $appCookies: any beforeEach(() => { vi.clearAllMocks() // Mock Pinia stores const mockStoreA = { $reset: vi.fn(), $id: 'storeA' } const mockStoreB = { $reset: vi.fn(), $id: 'storeB' } mockPiniaInstance._s.set('storeA', mockStoreA as unknown as Store) mockPiniaInstance._s.set('storeB', mockStoreB as unknown as Store) // Mock getActivePinia to return the mocked Pinia instance vi.mocked(getActivePinia).mockReturnValue(mockPiniaInstance) $appCookies = useNuxtApp().$appCookies }) afterEach(() => { vi.clearAllMocks() }) it('should throw an error if there is no active Pinia instance', () => { vi.mocked(getActivePinia).mockReturnValue(null) // No active Pinia instance expect(() => useResetStore()).toThrow('There is no active Pinia instance') }) it('should create reset functions for each store', () => { const resetStores = useResetStore() expect(resetStores).toHaveProperty('storeA') expect(resetStores).toHaveProperty('storeB') // Call the reset function for storeA resetStores.storeA() expect(mockPiniaInstance._s.get('storeA').$reset).toHaveBeenCalled() // Call the reset function for storeB resetStores.storeB() expect(mockPiniaInstance._s.get('storeB').$reset).toHaveBeenCalled() }) it('should reset all stores and clear authentication data', () => { const resetStores = useResetStore() global.process = { ...global.process, client: true, } vi.useFakeTimers() resetStores.all() // Simulate the timeout for setTokenCookie vi.advanceTimersByTime(1000) expect($appCookies.token.value).toEqual('') // Ensure all stores are reset except those in LIST_STORE_EXCLUDE_RESET mockPiniaInstance._s.forEach((store, name) => { if (!LIST_STORE_EXCLUDE_RESET.includes(name)) { expect(store.$reset).toHaveBeenCalled() } else { expect(store.$reset).not.toHaveBeenCalled() } }) }) })