test: full test coverage of baseFontStore and unifiedFontStore
All checks were successful
Workflow / build (pull_request) Successful in 55s
Workflow / publish (pull_request) Has been skipped

This commit is contained in:
Ilia Mashkov
2026-04-08 09:33:04 +03:00
parent 9c538069e4
commit 752e38adf9
6 changed files with 1208 additions and 531 deletions

View File

@@ -0,0 +1,644 @@
import { QueryClient } from '@tanstack/query-core';
import { flushSync } from 'svelte';
import {
afterEach,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest';
import { generateMockFonts } from '../../../lib/mocks/fonts.mock';
import type { UnifiedFont } from '../../types';
import { BaseFontStore } from './baseFontStore.svelte';
vi.mock('$shared/api/queryClient', () => ({
queryClient: new QueryClient({
defaultOptions: {
queries: {
retry: 0,
gcTime: 0,
},
},
}),
}));
import { queryClient } from '$shared/api/queryClient';
interface TestParams {
limit?: number;
offset?: number;
q?: string;
providers?: string[];
categories?: string[];
subsets?: string[];
}
class TestFontStore extends BaseFontStore<TestParams> {
protected getQueryKey(params: TestParams) {
return ['testFonts', params] as const;
}
protected async fetchFn(params: TestParams): Promise<UnifiedFont[]> {
return generateMockFonts(params.limit || 10);
}
}
describe('baseFontStore', () => {
describe('constructor', () => {
afterEach(() => {
queryClient.clear();
vi.resetAllMocks();
});
it('creates a new store with initial params', () => {
const store = new TestFontStore({ limit: 20, offset: 10 });
expect(store.params.limit).toBe(20);
expect(store.params.offset).toBe(10);
store.destroy();
});
it('defaults offset to 0 if not provided', () => {
const store = new TestFontStore({ limit: 10 });
expect(store.params.offset).toBe(0);
store.destroy();
});
it('initializes observer with query options', () => {
const store = new TestFontStore({ limit: 10 });
expect((store as any).observer).toBeDefined();
store.destroy();
});
});
describe('params getter', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10, offset: 0 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('returns merged internal params', () => {
store.setParams({ limit: 20 });
flushSync();
expect(store.params.limit).toBe(20);
expect(store.params.offset).toBe(0);
});
it('defaults offset to 0 when undefined', () => {
const store2 = new TestFontStore({});
flushSync();
expect(store2.params.offset).toBe(0);
store2.destroy();
});
});
describe('state getters', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
describe('fonts', () => {
it('returns fonts after auto-fetch on mount', async () => {
await new Promise(resolve => setTimeout(resolve, 0));
expect(store.fonts).toHaveLength(10);
});
it('returns fonts when data is loaded', async () => {
await store.refetch();
flushSync();
expect(store.fonts).toHaveLength(10);
});
it('returns fonts when data is loaded', async () => {
await store.refetch();
flushSync();
expect(store.fonts).toHaveLength(10);
});
});
describe('isLoading', () => {
it('is false after initial fetch completes', async () => {
await store.refetch();
flushSync();
expect(store.isLoading).toBe(false);
});
it('is false when error occurs', async () => {
vi.spyOn(store, 'fetchFn' as any).mockRejectedValue(new Error('fail'));
await store.refetch().catch(() => {});
flushSync();
expect(store.isLoading).toBe(false);
});
});
describe('isFetching', () => {
it('is false after fetch completes', async () => {
await store.refetch();
flushSync();
expect(store.isFetching).toBe(false);
});
it('is true during refetch', async () => {
await store.refetch();
flushSync();
const refetchPromise = store.refetch();
flushSync();
expect(store.isFetching).toBe(true);
await refetchPromise;
});
});
describe('isError', () => {
it('is false initially', () => {
expect(store.isError).toBe(false);
});
it('is true after fetch error', async () => {
vi.spyOn(store, 'fetchFn' as any).mockRejectedValue(new Error('fail'));
await store.refetch().catch(() => {});
flushSync();
expect(store.isError).toBe(true);
});
it('is false after successful fetch', async () => {
await store.refetch();
flushSync();
expect(store.isError).toBe(false);
});
});
describe('error', () => {
it('is null initially', () => {
expect(store.error).toBeNull();
});
it('returns error object after fetch error', async () => {
const testError = new Error('test error');
vi.spyOn(store, 'fetchFn' as any).mockRejectedValue(testError);
await store.refetch().catch(() => {});
flushSync();
expect(store.error).toBe(testError);
});
it('is null after successful fetch', async () => {
await store.refetch();
flushSync();
expect(store.error).toBeNull();
});
});
describe('isEmpty', () => {
it('is true when no fonts loaded and not loading', async () => {
await store.refetch();
flushSync();
store.setQueryData(() => []);
flushSync();
expect(store.isEmpty).toBe(true);
});
it('is false when fonts are present', async () => {
await store.refetch();
flushSync();
expect(store.isEmpty).toBe(false);
});
it('is false when loading', () => {
expect(store.isEmpty).toBe(false);
});
});
});
describe('setParams', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10, offset: 0 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('merges new params with existing', () => {
store.setParams({ limit: 20 });
flushSync();
expect(store.params.limit).toBe(20);
expect(store.params.offset).toBe(0);
});
it('replaces existing param values', () => {
store.setParams({ limit: 30 });
flushSync();
store.setParams({ limit: 40 });
flushSync();
expect(store.params.limit).toBe(40);
});
it('triggers observer options update', async () => {
const setOptionsSpy = vi.spyOn((store as any).observer, 'setOptions');
store.setParams({ limit: 20 });
flushSync();
expect(setOptionsSpy).toHaveBeenCalled();
});
});
describe('updateInternalParams', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10, offset: 20 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('updates internal params without triggering setParams hooks', () => {
(store as any).updateInternalParams({ offset: 0 });
flushSync();
expect(store.params.offset).toBe(0);
expect(store.params.limit).toBe(10);
});
it('merges with existing internal params', () => {
(store as any).updateInternalParams({ offset: 0, limit: 30 });
flushSync();
expect(store.params.offset).toBe(0);
expect(store.params.limit).toBe(30);
});
it('updates observer options', () => {
const setOptionsSpy = vi.spyOn((store as any).observer, 'setOptions');
(store as any).updateInternalParams({ offset: 0 });
flushSync();
expect(setOptionsSpy).toHaveBeenCalled();
});
});
describe('invalidate', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('invalidates query for current params', async () => {
await store.refetch();
flushSync();
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
store.invalidate();
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: ['testFonts', store.params],
});
});
it('triggers refetch of invalidated query', async () => {
await store.refetch();
flushSync();
const fetchSpy = vi.spyOn(store, 'fetchFn' as any);
store.invalidate();
await store.refetch();
flushSync();
expect(fetchSpy).toHaveBeenCalled();
});
});
describe('destroy', () => {
it('calls cleanup function', () => {
const store = new TestFontStore({ limit: 10 });
const cleanupSpy = vi.spyOn(store, 'cleanup' as any);
store.destroy();
expect(cleanupSpy).toHaveBeenCalled();
});
it('can be called multiple times without error', () => {
const store = new TestFontStore({ limit: 10 });
expect(() => {
store.destroy();
store.destroy();
}).not.toThrow();
});
});
describe('refetch', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('triggers a refetch', async () => {
const fetchSpy = vi.spyOn(store, 'fetchFn' as any);
await store.refetch();
flushSync();
expect(fetchSpy).toHaveBeenCalled();
});
it('updates observer options before refetching', async () => {
const setOptionsSpy = vi.spyOn((store as any).observer, 'setOptions');
const refetchSpy = vi.spyOn((store as any).observer, 'refetch');
await store.refetch();
flushSync();
expect(setOptionsSpy).toHaveBeenCalledBefore(refetchSpy);
});
it('uses current params for refetch', async () => {
store.setParams({ limit: 20 });
flushSync();
await store.refetch();
flushSync();
expect(store.params.limit).toBe(20);
});
});
describe('prefetch', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('prefetches data with provided params', async () => {
const prefetchSpy = vi.spyOn(queryClient, 'prefetchQuery');
await store.prefetch({ limit: 20, offset: 0 });
expect(prefetchSpy).toHaveBeenCalled();
});
it('stores prefetched data in cache', async () => {
queryClient.clear();
const store2 = new TestFontStore({ limit: 10 });
await store2.prefetch({ limit: 5, offset: 0 });
flushSync();
const cached = store2.getCachedData();
expect(cached).toBeDefined();
expect(cached?.length).toBeGreaterThanOrEqual(0);
store2.destroy();
});
});
describe('cancel', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('cancels ongoing queries', () => {
const cancelSpy = vi.spyOn(queryClient, 'cancelQueries');
store.cancel();
expect(cancelSpy).toHaveBeenCalledWith({
queryKey: ['testFonts', store.params],
});
});
});
describe('getCachedData', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('returns undefined when no data cached', () => {
queryClient.clear();
const store2 = new TestFontStore({ limit: 10 });
expect(store2.getCachedData()).toBeUndefined();
store2.destroy();
});
it('returns cached data after fetch', async () => {
await store.refetch();
flushSync();
const cached = store.getCachedData();
expect(cached).toHaveLength(10);
});
it('returns data from manual cache update', () => {
store.setQueryData(() => [generateMockFonts(1)[0]]);
flushSync();
const cached = store.getCachedData();
expect(cached).toHaveLength(1);
});
});
describe('setQueryData', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('sets data in cache', () => {
store.setQueryData(() => [generateMockFonts(1)[0]]);
flushSync();
const cached = store.getCachedData();
expect(cached).toHaveLength(1);
});
it('updates existing cached data', async () => {
await store.refetch();
flushSync();
store.setQueryData(old => [...(old || []), generateMockFonts(1)[0]]);
flushSync();
const cached = store.getCachedData();
expect(cached).toHaveLength(11);
});
it('receives previous data in updater function', async () => {
await store.refetch();
flushSync();
const updater = vi.fn((old: UnifiedFont[] | undefined) => old || []);
store.setQueryData(updater);
flushSync();
expect(updater).toHaveBeenCalledWith(expect.any(Array));
});
});
describe('getOptions', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('returns query options with query key', () => {
const options = (store as any).getOptions();
expect(options.queryKey).toEqual(['testFonts', store.params]);
});
it('returns query options with query fn', () => {
const options = (store as any).getOptions();
expect(options.queryFn).toBeDefined();
});
it('uses provided params when passed', () => {
const customParams = { limit: 20, offset: 0 };
const options = (store as any).getOptions(customParams);
expect(options.queryKey).toEqual(['testFonts', customParams]);
});
it('has default staleTime and gcTime', () => {
const options = (store as any).getOptions();
expect(options.staleTime).toBe(5 * 60 * 1000);
expect(options.gcTime).toBe(10 * 60 * 1000);
});
});
describe('observer integration', () => {
let store: TestFontStore;
beforeEach(() => {
store = new TestFontStore({ limit: 10 });
});
afterEach(() => {
store.destroy();
queryClient.clear();
vi.resetAllMocks();
});
it('syncs observer state to Svelte state', async () => {
await store.refetch();
flushSync();
expect(store.fonts).toHaveLength(10);
});
it('observer syncs on state changes', async () => {
await store.refetch();
flushSync();
expect((store as any).result.data).toHaveLength(10);
});
});
describe('effect cleanup', () => {
it('cleanup function is set on constructor', () => {
const store = new TestFontStore({ limit: 10 });
expect(store.cleanup).toBeDefined();
expect(typeof store.cleanup).toBe('function');
store.destroy();
});
});
});

View File

@@ -23,25 +23,22 @@ export abstract class BaseFontStore<TParams extends Record<string, any>> {
*/
cleanup: () => void;
/** Reactive parameter bindings from external sources */
#bindings = $state<(() => Partial<TParams>)[]>([]);
/** Internal parameter state */
#internalParams = $state<TParams>({} as TParams);
/**
* Merged params from internal state and all bindings
* Automatically updates when bindings or internal params change
* Merged params from internal state
* Computed synchronously on access
*/
params = $derived.by(() => {
let merged = { ...this.#internalParams };
// Merge all binding results into params
for (const getter of this.#bindings) {
const bindingResult = getter();
merged = { ...merged, ...bindingResult };
get params(): TParams {
// Default offset to 0 if undefined (for pagination methods)
let result = this.#internalParams as TParams;
if (result.offset === undefined) {
result = { ...result, offset: 0 } as TParams;
}
return merged as TParams;
});
return result;
}
/** TanStack Query result state */
protected result = $state<QueryObserverResult<UnifiedFont[], Error>>({} as any);
@@ -89,9 +86,10 @@ export abstract class BaseFontStore<TParams extends Record<string, any>> {
* @param params - Query parameters (defaults to current params)
*/
protected getOptions(params = this.params): QueryObserverOptions<UnifiedFont[], Error> {
// Always use current params, not the captured closure params
return {
queryKey: this.getQueryKey(params),
queryFn: () => this.fetchFn(params),
queryFn: () => this.fetchFn(this.params),
staleTime: 5 * 60 * 1000,
gcTime: 10 * 60 * 1000,
};
@@ -127,25 +125,25 @@ export abstract class BaseFontStore<TParams extends Record<string, any>> {
return !this.isLoading && this.fonts.length === 0;
}
/**
* Add a reactive parameter binding
* @param getter - Function that returns partial params to merge
* @returns Unbind function to remove the binding
*/
addBinding(getter: () => Partial<TParams>) {
this.#bindings.push(getter);
return () => {
this.#bindings = this.#bindings.filter(b => b !== getter);
};
}
/**
* Update query parameters
* @param newParams - Partial params to merge with existing
*/
setParams(newParams: Partial<TParams>) {
this.#internalParams = { ...this.params, ...newParams };
this.#internalParams = { ...this.#internalParams, ...newParams };
// Manually update observer options since effects may not run in test contexts
this.observer.setOptions(this.getOptions());
}
/**
* Update internal params without triggering setParams hooks
* Used for resetting offset when filters change
* @param newParams - Partial params to merge with existing
*/
protected updateInternalParams(newParams: Partial<TParams>) {
this.#internalParams = { ...this.#internalParams, ...newParams };
// Update observer options
this.observer.setOptions(this.getOptions());
}
/**
@@ -166,6 +164,8 @@ export abstract class BaseFontStore<TParams extends Record<string, any>> {
* Manually trigger a refetch
*/
async refetch() {
// Update options before refetching to ensure current params are used
this.observer.setOptions(this.getOptions());
await this.observer.refetch();
}
@@ -185,15 +185,6 @@ export abstract class BaseFontStore<TParams extends Record<string, any>> {
});
}
/**
* Clear cache for current params
*/
clearCache() {
this.qc.removeQueries({
queryKey: this.getQueryKey(this.params),
});
}
/**
* Get cached data without triggering fetch
*/