miracoly
miracoly
NNuxt
Created by miracoly on 4/24/2024 in #❓・help
Mocking Pinia Store in Vitest Component Test
Thanks for the idea! I was able to mock it with mockNuxtImport() and vitest's mock functionality.
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { mockNuxtImport, renderSuspended } from '@nuxt/test-utils/runtime';
import { screen } from '@testing-library/vue';

const { useLeagueStoreMock, retrieveAllLeagues } = vi.hoisted(
() => ({
useLeagueStoreMock: vi.fn<any, Partial<LeagueStoreTree>>(),
retrieveAllLeagues: vi.fn(),
}),
);

retrieveAllLeagues.mockImplementation(async (): Promise<void> => {
await Promise.resolve();
});

mockNuxtImport('useLeagueStore', () => useLeagueStoreMock);

beforeEach(() => {
useLeagueStoreMock.mockRestore();
});

describe('foo', () => {
beforeEach(async () => {
useLeagueStoreMock.mockImplementation(() => ({
allLeagues: computed(() => [...]),
retrieveAllLeagues,
}));
});

test('initializes allLeagues state', async () => {
await renderSuspended(DashboardPage);
...
});
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { mockNuxtImport, renderSuspended } from '@nuxt/test-utils/runtime';
import { screen } from '@testing-library/vue';

const { useLeagueStoreMock, retrieveAllLeagues } = vi.hoisted(
() => ({
useLeagueStoreMock: vi.fn<any, Partial<LeagueStoreTree>>(),
retrieveAllLeagues: vi.fn(),
}),
);

retrieveAllLeagues.mockImplementation(async (): Promise<void> => {
await Promise.resolve();
});

mockNuxtImport('useLeagueStore', () => useLeagueStoreMock);

beforeEach(() => {
useLeagueStoreMock.mockRestore();
});

describe('foo', () => {
beforeEach(async () => {
useLeagueStoreMock.mockImplementation(() => ({
allLeagues: computed(() => [...]),
retrieveAllLeagues,
}));
});

test('initializes allLeagues state', async () => {
await renderSuspended(DashboardPage);
...
});
That does the trick. In my component, I utilize callOnce, and it appears to truly execute only once within a single test file. That's why retrieveAllLeagues isn't restored with mockRestore(). I suppose if someone wants to ensure the correct methods are called with callOnce, they either need to assert them in the proper sequence or employ multiple test files.
2 replies