Implement LocalStorageMock for testing

This commit is contained in:
2025-12-07 17:16:40 +01:00
parent 54fe0f7421
commit 00a502a268

View File

@@ -1,10 +1,44 @@
import '@testing-library/jest-dom' import '@testing-library/jest-dom'
import { afterEach, vi } from 'vitest' import { afterEach, beforeEach } from 'vitest'
// Mock fetch globally since your app uses fetch // Create a working localStorage implementation for tests
global.fetch = vi.fn() // This ensures localStorage works in both CLI and VSCode test runner
class LocalStorageMock implements Storage {
private store: Map<string, string> = new Map()
get length(): number {
return this.store.size
}
clear(): void {
this.store.clear()
}
getItem(key: string): string | null {
return this.store.get(key) ?? null
}
key(index: number): string | null {
return Array.from(this.store.keys())[index] ?? null
}
removeItem(key: string): void {
this.store.delete(key)
}
setItem(key: string, value: string): void {
this.store.set(key, value)
}
}
// Replace global localStorage
global.localStorage = new LocalStorageMock()
// Clean up before each test
beforeEach(() => {
localStorage.clear()
})
// Clean up after each test
afterEach(() => { afterEach(() => {
vi.clearAllMocks() localStorage.clear()
}) })