import { useIntroStore } from '@/stores/intro.store'; import { beforeEach } from '@vitest/runner'; import { flushPromises } from '@vue/test-utils'; import { createPinia, setActivePinia, storeToRefs } from 'pinia'; import { onMounted } from 'vue'; vi.mock('vue', async (importOriginal) => { return { ...(await importOriginal()), onMounted: vi.fn(), }; }); describe('intro store', () => { beforeEach(() => { vi.restoreAllMocks(); setActivePinia(createPinia()); }); const localStorageMock = (() => { let store: { [key: string]: string } = {}; return { getItem: vi.fn().mockReturnValue((key: string) => store[key] || null), setItem: vi.fn().mockImplementation((key: string, value: string) => { store[key] = value.toString(); }), }; })(); Object.defineProperty(window, 'localStorage', { value: localStorageMock, }); beforeEach(() => { localStorageMock.getItem.mockClear(); localStorageMock.setItem.mockClear(); }); it('should show intro by default', () => { const { dontShowAgain } = storeToRefs(useIntroStore()); expect(dontShowAgain.value).toBeFalsy(); }); it('should persist to local storage', async () => { const { dontShowAgain } = storeToRefs(useIntroStore()); await flushPromises(); dontShowAgain.value = true; dontShowAgain.value = false; await flushPromises(); expect(localStorageMock.setItem).toHaveBeenCalledWith( expect.any(String), 'true', ); }); it('should mount and set from storage true', () => { localStorageMock.getItem.mockReturnValue(true); const spy = vi.mocked(onMounted).mockImplementation((fn: any) => { fn(); }); const { dontShowAgain } = storeToRefs(useIntroStore()); expect(spy).toHaveBeenCalled(); expect(dontShowAgain.value).toBe(true); }); it('should mount and set from storage false', () => { localStorageMock.getItem.mockReturnValue(false); const spy = vi.mocked(onMounted).mockImplementation((fn: any) => { fn(); }); const { dontShowAgain } = storeToRefs(useIntroStore()); expect(spy).toHaveBeenCalled(); expect(dontShowAgain.value).toBe(false); }); it('should mount and set from storage fail', () => { const consoleWarnSpy = vi .spyOn(console, 'error') .mockImplementation(() => {}); localStorageMock.getItem.mockReturnValue('not a json'); const spy = vi.mocked(onMounted).mockImplementation((fn: any) => { fn(); }); const { dontShowAgain } = storeToRefs(useIntroStore()); expect(spy).toHaveBeenCalled(); expect(consoleWarnSpy).toHaveBeenCalledWith( 'Error parsing stored value:', expect.anything(), ); expect(dontShowAgain.value).toBe(false); }); it('should mount and set from storage empty', () => { const consoleWarnSpy = vi .spyOn(console, 'error') .mockImplementation(() => {}); localStorageMock.getItem.mockReturnValue(null); const spy = vi.mocked(onMounted).mockImplementation((fn: any) => { fn(); }); const { dontShowAgain } = storeToRefs(useIntroStore()); expect(spy).toHaveBeenCalled(); expect(consoleWarnSpy).not.toHaveBeenCalledWith( 'Error parsing stored value:', expect.any(Error), ); expect(dontShowAgain.value).toBe(false); }); });