|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; |
| 2 | + |
| 3 | +import { getTheme, initTheme, setTheme, subscribeTheme } from './theme'; |
| 4 | + |
| 5 | +describe('theme module', () => { |
| 6 | + beforeEach(() => { |
| 7 | + localStorage.clear(); |
| 8 | + delete document.documentElement.dataset.theme; |
| 9 | + }); |
| 10 | + |
| 11 | + afterEach(() => { |
| 12 | + localStorage.clear(); |
| 13 | + delete document.documentElement.dataset.theme; |
| 14 | + }); |
| 15 | + |
| 16 | + it('defaults to "light" when localStorage has no value', () => { |
| 17 | + expect(getTheme()).toBe('light'); |
| 18 | + }); |
| 19 | + |
| 20 | + it('reads the persisted value from localStorage', () => { |
| 21 | + localStorage.setItem('wb-theme', 'dark'); |
| 22 | + expect(getTheme()).toBe('dark'); |
| 23 | + }); |
| 24 | + |
| 25 | + it('falls back to "light" for an empty or unrecognized stored value', () => { |
| 26 | + localStorage.setItem('wb-theme', ''); |
| 27 | + expect(getTheme()).toBe('light'); |
| 28 | + |
| 29 | + localStorage.setItem('wb-theme', 'Dark'); |
| 30 | + expect(getTheme()).toBe('light'); |
| 31 | + }); |
| 32 | + |
| 33 | + it('setTheme updates localStorage and the document attribute', () => { |
| 34 | + setTheme('dark'); |
| 35 | + |
| 36 | + expect(localStorage.getItem('wb-theme')).toBe('dark'); |
| 37 | + expect(document.documentElement.dataset.theme).toBe('dark'); |
| 38 | + expect(getTheme()).toBe('dark'); |
| 39 | + }); |
| 40 | + |
| 41 | + it('setTheme notifies subscribers', () => { |
| 42 | + const listener = vi.fn(); |
| 43 | + const unsubscribe = subscribeTheme(listener); |
| 44 | + |
| 45 | + setTheme('dark'); |
| 46 | + |
| 47 | + expect(listener).toHaveBeenCalledTimes(1); |
| 48 | + unsubscribe(); |
| 49 | + }); |
| 50 | + |
| 51 | + it('setTheme does NOT notify subscribers when the value is unchanged', () => { |
| 52 | + setTheme('light'); |
| 53 | + const listener = vi.fn(); |
| 54 | + const unsubscribe = subscribeTheme(listener); |
| 55 | + |
| 56 | + setTheme('light'); |
| 57 | + |
| 58 | + expect(listener).not.toHaveBeenCalled(); |
| 59 | + unsubscribe(); |
| 60 | + }); |
| 61 | + |
| 62 | + it('initTheme applies the persisted theme to the DOM without a toggle', () => { |
| 63 | + localStorage.setItem('wb-theme', 'dark'); |
| 64 | + delete document.documentElement.dataset.theme; |
| 65 | + |
| 66 | + initTheme(); |
| 67 | + |
| 68 | + expect(document.documentElement.dataset.theme).toBe('dark'); |
| 69 | + }); |
| 70 | + |
| 71 | + it('unsubscribe removes the listener', () => { |
| 72 | + const listener = vi.fn(); |
| 73 | + const unsubscribe = subscribeTheme(listener); |
| 74 | + unsubscribe(); |
| 75 | + |
| 76 | + setTheme('dark'); |
| 77 | + |
| 78 | + expect(listener).not.toHaveBeenCalled(); |
| 79 | + }); |
| 80 | +}); |
0 commit comments