mirror of
https://github.com/jamiepine/voicebox.git
synced 2026-09-18 22:30:40 -07:00
test: vitest foundation with browser mode
Two projects in one root config: 'unit' (happy-dom) for stores, hooks, and utils, and 'browser' (real Chromium via the playwright provider) for component tests — no jsdom polyfills for EventSource, AudioContext, or canvas. Harness pieces: createMockPlatform (spy-able Platform with an updater emit handle), renderWithProviders (fresh QueryClient with polling disabled + PlatformProvider), MSW worker with baseline health handler, and a store-reset teardown covering all eight zustand stores. Seed tests cover uiStore theme, serverStore invalidation, and an AboutPage render in Chromium. Requires node >= 20 (.node-version added); run with bun run test.
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
import { expect, it } from 'vitest';
|
||||
import { AboutPage } from '@/components/ServerTab/AboutPage';
|
||||
import { createMockPlatform } from '@/test/mockPlatform';
|
||||
import { renderWithProviders } from '@/test/render';
|
||||
|
||||
it('renders and shows the platform version', async () => {
|
||||
const platform = createMockPlatform({
|
||||
metadata: { getVersion: async () => '9.9.9-test', isTauri: false },
|
||||
});
|
||||
|
||||
const screen = await renderWithProviders(<AboutPage />, { platform });
|
||||
|
||||
await expect.element(screen.getByAltText('Voicebox')).toBeVisible();
|
||||
await expect.element(screen.getByText('9.9.9-test', { exact: false })).toBeVisible();
|
||||
});
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { queryClient } from '@/lib/queryClient';
|
||||
import { isLoopbackVoiceboxServerUrl, useServerStore } from '@/stores/serverStore';
|
||||
|
||||
describe('serverStore', () => {
|
||||
it('invalidates all queries when the server url changes', () => {
|
||||
const spy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
useServerStore.getState().setServerUrl('http://10.0.0.5:17493');
|
||||
|
||||
expect(useServerStore.getState().serverUrl).toBe('http://10.0.0.5:17493');
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not invalidate queries when the url is unchanged', () => {
|
||||
const url = useServerStore.getState().serverUrl;
|
||||
const spy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
useServerStore.getState().setServerUrl(url);
|
||||
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isLoopbackVoiceboxServerUrl', () => {
|
||||
it('matches loopback hosts on the voicebox port', () => {
|
||||
expect(isLoopbackVoiceboxServerUrl('http://127.0.0.1:17493')).toBe(true);
|
||||
expect(isLoopbackVoiceboxServerUrl('http://localhost:17493')).toBe(true);
|
||||
expect(isLoopbackVoiceboxServerUrl('http://[::1]:17493')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects other hosts, ports, and junk', () => {
|
||||
expect(isLoopbackVoiceboxServerUrl('http://10.0.0.5:17493')).toBe(false);
|
||||
expect(isLoopbackVoiceboxServerUrl('http://127.0.0.1:8000')).toBe(false);
|
||||
expect(isLoopbackVoiceboxServerUrl('not a url')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
|
||||
describe('uiStore', () => {
|
||||
it('applies the dark class when theme is set to dark', () => {
|
||||
useUIStore.getState().setTheme('dark');
|
||||
|
||||
expect(useUIStore.getState().theme).toBe('dark');
|
||||
expect(document.documentElement.classList.contains('dark')).toBe(true);
|
||||
});
|
||||
|
||||
it('removes the dark class when theme is set to light', () => {
|
||||
useUIStore.getState().setTheme('dark');
|
||||
useUIStore.getState().setTheme('light');
|
||||
|
||||
expect(document.documentElement.classList.contains('dark')).toBe(false);
|
||||
});
|
||||
|
||||
it('persists only theme and selectedProfileId', () => {
|
||||
useUIStore.getState().setTheme('light');
|
||||
useUIStore.getState().setSidebarOpen(false);
|
||||
useUIStore.getState().setSelectedEngine('kokoro');
|
||||
|
||||
const persisted = JSON.parse(localStorage.getItem('voicebox-ui') ?? '{}');
|
||||
expect(persisted.state).toEqual({ selectedProfileId: null, theme: 'light' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { vi } from 'vitest';
|
||||
import type { Platform, UpdateStatus } from '@/platform/types';
|
||||
|
||||
export interface MockPlatform extends Platform {
|
||||
/** Push a new updater status to all subscribers, as the real updater would. */
|
||||
emitUpdateStatus(status: UpdateStatus): void;
|
||||
}
|
||||
|
||||
export interface MockPlatformOverrides {
|
||||
filesystem?: Partial<Platform['filesystem']>;
|
||||
updater?: Partial<Platform['updater']>;
|
||||
audio?: Partial<Platform['audio']>;
|
||||
lifecycle?: Partial<Platform['lifecycle']>;
|
||||
metadata?: Partial<Platform['metadata']>;
|
||||
}
|
||||
|
||||
const INITIAL_UPDATE_STATUS: UpdateStatus = {
|
||||
checking: false,
|
||||
available: false,
|
||||
downloading: false,
|
||||
installing: false,
|
||||
readyToInstall: false,
|
||||
};
|
||||
|
||||
export const TEST_SERVER_URL = 'http://127.0.0.1:17493';
|
||||
|
||||
/**
|
||||
* A fully spy-able Platform. Every method is a vi.fn with a benign default
|
||||
* (browser-like: no system audio, isTauri false), so tests can assert calls
|
||||
* or override behavior per section via `overrides`.
|
||||
*/
|
||||
export function createMockPlatform(overrides: MockPlatformOverrides = {}): MockPlatform {
|
||||
let updateStatus = { ...INITIAL_UPDATE_STATUS };
|
||||
const subscribers = new Set<(status: UpdateStatus) => void>();
|
||||
|
||||
return {
|
||||
filesystem: {
|
||||
saveFile: vi.fn(async (filename: string) => filename),
|
||||
openPath: vi.fn(async () => {}),
|
||||
pickDirectory: vi.fn(async () => null),
|
||||
...overrides.filesystem,
|
||||
},
|
||||
updater: {
|
||||
checkForUpdates: vi.fn(async () => {}),
|
||||
downloadAndInstall: vi.fn(async () => {}),
|
||||
restartAndInstall: vi.fn(async () => {}),
|
||||
getStatus: vi.fn(() => ({ ...updateStatus })),
|
||||
subscribe: vi.fn((callback: (status: UpdateStatus) => void) => {
|
||||
subscribers.add(callback);
|
||||
callback(updateStatus);
|
||||
return () => {
|
||||
subscribers.delete(callback);
|
||||
};
|
||||
}),
|
||||
...overrides.updater,
|
||||
},
|
||||
audio: {
|
||||
isSystemAudioSupported: vi.fn(async () => false),
|
||||
startSystemAudioCapture: vi.fn(async () => {}),
|
||||
stopSystemAudioCapture: vi.fn(async () => new Blob()),
|
||||
listOutputDevices: vi.fn(async () => []),
|
||||
playToDevices: vi.fn(async () => {}),
|
||||
stopPlayback: vi.fn(),
|
||||
...overrides.audio,
|
||||
},
|
||||
lifecycle: {
|
||||
startServer: vi.fn(async () => TEST_SERVER_URL),
|
||||
stopServer: vi.fn(async () => {}),
|
||||
restartServer: vi.fn(async () => TEST_SERVER_URL),
|
||||
setKeepServerRunning: vi.fn(async () => {}),
|
||||
setBackendOverride: vi.fn(async () => {}),
|
||||
setupWindowCloseHandler: vi.fn(async () => {}),
|
||||
subscribeToServerLogs: vi.fn(() => () => {}),
|
||||
...overrides.lifecycle,
|
||||
},
|
||||
metadata: {
|
||||
getVersion: vi.fn(async () => '0.0.0-test'),
|
||||
isTauri: false,
|
||||
...overrides.metadata,
|
||||
},
|
||||
emitUpdateStatus(status: UpdateStatus) {
|
||||
updateStatus = { ...status };
|
||||
for (const callback of subscribers) callback(updateStatus);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { type HttpHandler, HttpResponse, http } from 'msw';
|
||||
|
||||
/**
|
||||
* Baseline handlers for endpoints nearly every screen touches. The health
|
||||
* payload mirrors backend/routes/health.py closely enough for the UI's
|
||||
* checks (`status`, `model_loaded`, backend variant fields).
|
||||
*/
|
||||
export const serverHandlers: HttpHandler[] = [
|
||||
http.get('*/health', () =>
|
||||
HttpResponse.json({
|
||||
status: 'ok',
|
||||
model_loaded: false,
|
||||
device: 'cpu',
|
||||
backend_variant: 'cpu',
|
||||
}),
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,9 @@
|
||||
import { setupWorker } from 'msw/browser';
|
||||
import { serverHandlers } from './handlers/server';
|
||||
|
||||
/**
|
||||
* Browser-mode MSW worker. Individual tests layer route-specific handlers
|
||||
* on top with `worker.use(...)`; `setup.browser.ts` resets them after each
|
||||
* test. Only the health/baseline handlers are registered globally.
|
||||
*/
|
||||
export const worker = setupWorker(...serverHandlers);
|
||||
@@ -0,0 +1,346 @@
|
||||
/* eslint-disable */
|
||||
/* tslint:disable */
|
||||
|
||||
/**
|
||||
* Mock Service Worker.
|
||||
* @see https://github.com/mswjs/msw
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.15.0';
|
||||
const INTEGRITY_CHECKSUM = '03cb67ac84128e63d7cd722a6e5b7f1e';
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse');
|
||||
const activeClientIds = new Set();
|
||||
|
||||
addEventListener('install', () => {
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
addEventListener('activate', (event) => {
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
|
||||
addEventListener('message', async (event) => {
|
||||
const clientId = Reflect.get(event.source || {}, 'id');
|
||||
|
||||
if (!clientId || !self.clients) {
|
||||
return;
|
||||
}
|
||||
|
||||
const client = await self.clients.get(clientId);
|
||||
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
});
|
||||
|
||||
switch (event.data) {
|
||||
case 'KEEPALIVE_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'KEEPALIVE_RESPONSE',
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'INTEGRITY_CHECK_REQUEST': {
|
||||
sendToClient(client, {
|
||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||
payload: {
|
||||
packageVersion: PACKAGE_VERSION,
|
||||
checksum: INTEGRITY_CHECKSUM,
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'MOCK_ACTIVATE': {
|
||||
activeClientIds.add(clientId);
|
||||
|
||||
sendToClient(client, {
|
||||
type: 'MOCKING_ENABLED',
|
||||
payload: {
|
||||
client: {
|
||||
id: client.id,
|
||||
frameType: client.frameType,
|
||||
},
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'CLIENT_CLOSED': {
|
||||
activeClientIds.delete(clientId);
|
||||
|
||||
const remainingClients = allClients.filter((client) => {
|
||||
return client.id !== clientId;
|
||||
});
|
||||
|
||||
// Unregister itself when there are no more clients
|
||||
if (remainingClients.length === 0) {
|
||||
self.registration.unregister();
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
addEventListener('fetch', (event) => {
|
||||
const requestInterceptedAt = Date.now();
|
||||
|
||||
// Bypass navigation requests.
|
||||
if (event.request.mode === 'navigate') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Opening the DevTools triggers the "only-if-cached" request
|
||||
// that cannot be handled by the worker. Bypass such requests.
|
||||
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Bypass all requests when there are no active clients.
|
||||
// Prevents the self-unregistered worked from handling requests
|
||||
// after it's been terminated (still remains active until the next reload).
|
||||
if (activeClientIds.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = crypto.randomUUID();
|
||||
event.respondWith(handleRequest(event, requestId, requestInterceptedAt));
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
*/
|
||||
async function handleRequest(event, requestId, requestInterceptedAt) {
|
||||
const client = await resolveMainClient(event);
|
||||
const requestCloneForEvents = event.request.clone();
|
||||
const response = await getResponse(event, client, requestId, requestInterceptedAt);
|
||||
|
||||
// Send back the response clone for the "response:*" life-cycle events.
|
||||
// Ensure MSW is active and ready to handle the message, otherwise
|
||||
// this message will pend indefinitely.
|
||||
if (client && activeClientIds.has(client.id)) {
|
||||
const serializedRequest = await serializeRequest(requestCloneForEvents);
|
||||
|
||||
// Omit the body of server-sent event stream responses.
|
||||
// Cloning such responses would prevent client-side stream cancelations
|
||||
// from reaching the original stream (a teed stream only cancels its
|
||||
// source once both of its branches cancel) and would buffer the
|
||||
// entire stream into the unconsumed clone indefinitely.
|
||||
const isEventStreamResponse = response.headers
|
||||
.get('content-type')
|
||||
?.toLowerCase()
|
||||
.startsWith('text/event-stream');
|
||||
|
||||
// Clone the response so both the client and the library could consume it.
|
||||
const responseClone = isEventStreamResponse ? null : response.clone();
|
||||
|
||||
sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'RESPONSE',
|
||||
payload: {
|
||||
isMockedResponse: IS_MOCKED_RESPONSE in response,
|
||||
request: {
|
||||
id: requestId,
|
||||
...serializedRequest,
|
||||
},
|
||||
response: {
|
||||
type: response.type,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: Object.fromEntries(response.headers.entries()),
|
||||
body: responseClone ? responseClone.body : null,
|
||||
},
|
||||
},
|
||||
},
|
||||
responseClone && responseClone.body ? [serializedRequest.body, responseClone.body] : [],
|
||||
);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the main client for the given event.
|
||||
* Client that issues a request doesn't necessarily equal the client
|
||||
* that registered the worker. It's with the latter the worker should
|
||||
* communicate with during the response resolving phase.
|
||||
* @param {FetchEvent} event
|
||||
* @returns {Promise<Client | undefined>}
|
||||
*/
|
||||
async function resolveMainClient(event) {
|
||||
const client = await self.clients.get(event.clientId);
|
||||
|
||||
if (activeClientIds.has(event.clientId)) {
|
||||
return client;
|
||||
}
|
||||
|
||||
if (client?.frameType === 'top-level') {
|
||||
return client;
|
||||
}
|
||||
|
||||
const allClients = await self.clients.matchAll({
|
||||
type: 'window',
|
||||
});
|
||||
|
||||
return allClients
|
||||
.filter((client) => {
|
||||
// Get only those clients that are currently visible.
|
||||
return client.visibilityState === 'visible';
|
||||
})
|
||||
.find((client) => {
|
||||
// Find the client ID that's recorded in the
|
||||
// set of clients that have registered the worker.
|
||||
return activeClientIds.has(client.id);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FetchEvent} event
|
||||
* @param {Client | undefined} client
|
||||
* @param {string} requestId
|
||||
* @param {number} requestInterceptedAt
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
async function getResponse(event, client, requestId, requestInterceptedAt) {
|
||||
// Clone the request because it might've been already used
|
||||
// (i.e. its body has been read and sent to the client).
|
||||
const requestClone = event.request.clone();
|
||||
|
||||
function passthrough() {
|
||||
// Cast the request headers to a new Headers instance
|
||||
// so the headers can be manipulated with.
|
||||
const headers = new Headers(requestClone.headers);
|
||||
|
||||
// Remove the "accept" header value that marked this request as passthrough.
|
||||
// This prevents request alteration and also keeps it compliant with the
|
||||
// user-defined CORS policies.
|
||||
const acceptHeader = headers.get('accept');
|
||||
if (acceptHeader) {
|
||||
const values = acceptHeader.split(',').map((value) => value.trim());
|
||||
const filteredValues = values.filter((value) => value !== 'msw/passthrough');
|
||||
|
||||
if (filteredValues.length > 0) {
|
||||
headers.set('accept', filteredValues.join(', '));
|
||||
} else {
|
||||
headers.delete('accept');
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(requestClone, { headers });
|
||||
}
|
||||
|
||||
// Bypass mocking when the client is not active.
|
||||
if (!client) {
|
||||
return passthrough();
|
||||
}
|
||||
|
||||
// Bypass initial page load requests (i.e. static assets).
|
||||
// The absence of the immediate/parent client in the map of the active clients
|
||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||
// and is not ready to handle requests.
|
||||
if (!activeClientIds.has(client.id)) {
|
||||
return passthrough();
|
||||
}
|
||||
|
||||
// Notify the client that a request has been intercepted.
|
||||
const serializedRequest = await serializeRequest(event.request);
|
||||
const clientMessage = await sendToClient(
|
||||
client,
|
||||
{
|
||||
type: 'REQUEST',
|
||||
payload: {
|
||||
id: requestId,
|
||||
interceptedAt: requestInterceptedAt,
|
||||
...serializedRequest,
|
||||
},
|
||||
},
|
||||
[serializedRequest.body],
|
||||
);
|
||||
|
||||
switch (clientMessage.type) {
|
||||
case 'MOCK_RESPONSE': {
|
||||
return respondWithMock(clientMessage.data);
|
||||
}
|
||||
|
||||
case 'PASSTHROUGH': {
|
||||
return passthrough();
|
||||
}
|
||||
}
|
||||
|
||||
return passthrough();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Client} client
|
||||
* @param {any} message
|
||||
* @param {Array<Transferable>} transferrables
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function sendToClient(client, message, transferrables = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const channel = new MessageChannel();
|
||||
|
||||
channel.port1.onmessage = (event) => {
|
||||
if (event.data && event.data.error) {
|
||||
return reject(event.data.error);
|
||||
}
|
||||
|
||||
resolve(event.data);
|
||||
};
|
||||
|
||||
client.postMessage(message, [channel.port2, ...transferrables.filter(Boolean)]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Response} response
|
||||
* @returns {Response}
|
||||
*/
|
||||
function respondWithMock(response) {
|
||||
// Setting response status code to 0 is a no-op.
|
||||
// However, when responding with a "Response.error()", the produced Response
|
||||
// instance will have status code set to 0. Since it's not possible to create
|
||||
// a Response instance with status code 0, handle that use-case separately.
|
||||
if (response.status === 0) {
|
||||
return Response.error();
|
||||
}
|
||||
|
||||
const mockedResponse = new Response(response.body, response);
|
||||
|
||||
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
|
||||
value: true,
|
||||
enumerable: true,
|
||||
});
|
||||
|
||||
return mockedResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Request} request
|
||||
*/
|
||||
async function serializeRequest(request) {
|
||||
return {
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
cache: request.cache,
|
||||
credentials: request.credentials,
|
||||
destination: request.destination,
|
||||
integrity: request.integrity,
|
||||
redirect: request.redirect,
|
||||
referrer: request.referrer,
|
||||
referrerPolicy: request.referrerPolicy,
|
||||
body: await request.arrayBuffer(),
|
||||
keepalive: request.keepalive,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { ReactNode } from 'react';
|
||||
import { render } from 'vitest-browser-react';
|
||||
import { PlatformProvider } from '@/platform/PlatformContext';
|
||||
import { createMockPlatform, type MockPlatform } from './mockPlatform';
|
||||
|
||||
export function createTestQueryClient(): QueryClient {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
// Retries and interval refetching are disabled so tests are
|
||||
// deterministic — polling components get their data exactly once.
|
||||
queries: {
|
||||
retry: false,
|
||||
refetchInterval: false,
|
||||
refetchOnWindowFocus: false,
|
||||
gcTime: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export interface RenderWithProvidersOptions {
|
||||
platform?: MockPlatform;
|
||||
queryClient?: QueryClient;
|
||||
}
|
||||
|
||||
export async function renderWithProviders(ui: ReactNode, options: RenderWithProvidersOptions = {}) {
|
||||
const platform = options.platform ?? createMockPlatform();
|
||||
const queryClient = options.queryClient ?? createTestQueryClient();
|
||||
|
||||
const result = await render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PlatformProvider platform={platform}>{ui}</PlatformProvider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
// Object.assign keeps the render result's prototype methods (locators)
|
||||
// intact — spreading would drop them.
|
||||
return Object.assign(result, { platform, queryClient });
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { queryClient } from '@/lib/queryClient';
|
||||
import { useAudioChannelStore } from '@/stores/audioChannelStore';
|
||||
import { useEffectsStore } from '@/stores/effectsStore';
|
||||
import { useGenerationStore } from '@/stores/generationStore';
|
||||
import { useLogStore } from '@/stores/logStore';
|
||||
import { usePlayerStore } from '@/stores/playerStore';
|
||||
import { useServerStore } from '@/stores/serverStore';
|
||||
import { useStoryStore } from '@/stores/storyStore';
|
||||
import { useUIStore } from '@/stores/uiStore';
|
||||
|
||||
const stores = [
|
||||
useAudioChannelStore,
|
||||
useEffectsStore,
|
||||
useGenerationStore,
|
||||
useLogStore,
|
||||
usePlayerStore,
|
||||
useServerStore,
|
||||
useStoryStore,
|
||||
useUIStore,
|
||||
] as const;
|
||||
|
||||
// Snapshot pristine state at module load, before any test mutates anything.
|
||||
const snapshots = stores.map((store) => store.getState());
|
||||
|
||||
/**
|
||||
* Restore every zustand store to its initial state and clear persisted
|
||||
* copies so tests can't leak state into each other. Persisted stores write
|
||||
* through to localStorage on setState, so localStorage is cleared last.
|
||||
*/
|
||||
export function resetAllStores(): void {
|
||||
stores.forEach((store, i) => {
|
||||
store.setState(snapshots[i] as never, true);
|
||||
});
|
||||
queryClient.clear();
|
||||
localStorage.clear();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { afterEach, beforeAll } from 'vitest';
|
||||
import { worker } from './msw/worker';
|
||||
|
||||
beforeAll(async () => {
|
||||
await worker.start({ onUnhandledRequest: 'error', quiet: true });
|
||||
return () => worker.stop();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
worker.resetHandlers();
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import '@/i18n';
|
||||
import { afterEach, vi } from 'vitest';
|
||||
import { resetAllStores } from './resetStores';
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
resetAllStores();
|
||||
});
|
||||
Reference in New Issue
Block a user