test: refactor ThemeService tests to use a mock localStorage implementation
This commit is contained in:
1 parent
38414e8656
commit
030d00ef67
1 file changed
+12
-3
@@ -3,7 +3,16 @@ import { vi } from 'vitest';
|
||||
import { ThemeService } from './theme.service';
|
||||
|
||||
describe('ThemeService', () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
const storage = new Map<string, string>();
|
||||
|
||||
beforeEach(() => {
|
||||
storage.clear();
|
||||
vi.stubGlobal('localStorage', {
|
||||
clear: () => storage.clear(),
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
@@ -25,14 +34,14 @@ describe('ThemeService', () => {
|
||||
'matchMedia',
|
||||
vi.fn(() => ({ matches: true, addEventListener: listener })),
|
||||
);
|
||||
localStorage.setItem('lmnp-theme', 'system');
|
||||
storage.set('lmnp-theme', 'system');
|
||||
const service = TestBed.inject(ThemeService);
|
||||
TestBed.tick();
|
||||
|
||||
expect(document.documentElement.dataset['theme']).toBe('dark');
|
||||
service.setPreference('light');
|
||||
TestBed.tick();
|
||||
expect(localStorage.getItem('lmnp-theme')).toBe('light');
|
||||
expect(storage.get('lmnp-theme')).toBe('light');
|
||||
expect(document.documentElement.dataset['themePreference']).toBe('light');
|
||||
expect(listener).toHaveBeenCalledWith('change', expect.any(Function));
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user