wxt-zustand
Version:
High-performance Zustand state management for WXT web extensions with seamless cross-tab synchronization and sub-10ms React re-renders
46 lines • 2.17 kB
JavaScript
import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { createStore } from 'zustand/vanilla';
// Mock @webext-core/proxy-service before importing modules that depend on it
const serviceObj = {};
const mockDefineProxyService = mock((_name, _factory) => {
return [mock(() => { }), mock(() => serviceObj)];
});
mock.module('@webext-core/proxy-service', () => ({
defineProxyService: mockDefineProxyService,
}));
const { syncInitialStateFromBackground } = await import('./initial');
describe('syncInitialStateFromBackground', () => {
beforeEach(() => {
mockDefineProxyService.mockClear();
for (const k of Object.keys(serviceObj))
delete serviceObj[k];
});
test('applies initial state to local store', async () => {
serviceObj.fetchInitialState = mock(async () => ({ count: 5 }));
const store = createStore(() => ({
count: 0,
}));
await syncInitialStateFromBackground('counter', store);
expect(store.getState().count).toBe(5);
expect(serviceObj.fetchInitialState).toHaveBeenCalledTimes(1);
});
test('uses readiness cache to avoid duplicate fetch', async () => {
serviceObj.fetchInitialState = mock(async () => ({ count: 10 }));
const store = createStore(() => ({
count: 0,
}));
// First call performs the fetch and sets state
await syncInitialStateFromBackground('counter', store);
expect(store.getState().count).toBe(10);
expect(serviceObj.fetchInitialState).toHaveBeenCalledTimes(1);
// Mutate the service to prove we don't fetch again
serviceObj.fetchInitialState = mock(async () => ({ count: 999 }));
await syncInitialStateFromBackground('counter', store);
expect(store.getState().count).toBe(10);
// Still only one call from the first initialization
// (connectAndFetchInitialState called exactly once due to readiness cache)
// Note: The second assigned mock is not invoked at all.
expect(serviceObj.fetchInitialState.mock.calls.length).toBe(0);
});
});
//# sourceMappingURL=initial.test.js.map