79 lines
2.5 KiB
TypeScript
79 lines
2.5 KiB
TypeScript
/**
|
|
* 15-persistence — localStorage 持久化
|
|
*
|
|
* 使用 vitest 原汁原味的 vi.spyOn() / vi.fn() 模式。
|
|
* 验证 Store 对 localStorage 的读写、损坏数据回退。
|
|
*/
|
|
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
|
import { store } from '../../src/composables/useStore'
|
|
|
|
describe('15-persistence — localStorage 持久化', () => {
|
|
beforeEach(() => {
|
|
localStorage.clear()
|
|
})
|
|
|
|
// ==================== 基本读写 ====================
|
|
describe('基本读写', () => {
|
|
it('get 不存在的 key 返回 fallback', () => {
|
|
expect(store.get('nonexistent', { hello: 'world' })).toEqual({ hello: 'world' })
|
|
})
|
|
|
|
it('set 后 get 返回正确值', () => {
|
|
store.set('test-key', { a: 1, b: [2, 3] })
|
|
expect(store.get('test-key', null)).toEqual({ a: 1, b: [2, 3] })
|
|
})
|
|
|
|
it('remove 后 get 返回 fallback', () => {
|
|
store.set('test-key', 'value')
|
|
store.remove('test-key')
|
|
expect(store.get('test-key', 'fallback')).toBe('fallback')
|
|
})
|
|
})
|
|
|
|
// ==================== clearAll ====================
|
|
describe('clearAll', () => {
|
|
it('清除所有带前缀的键,保留其他键', () => {
|
|
store.set('key1', 'a')
|
|
store.set('key2', 'b')
|
|
localStorage.setItem('other-key', 'keep-me')
|
|
|
|
store.clearAll()
|
|
|
|
expect(store.get('key1', null)).toBeNull()
|
|
expect(store.get('key2', null)).toBeNull()
|
|
expect(localStorage.getItem('other-key')).toBe('keep-me')
|
|
})
|
|
})
|
|
|
|
// ==================== 错误处理 ====================
|
|
describe('错误处理', () => {
|
|
it('损坏 JSON 数据回退默认值', () => {
|
|
localStorage.setItem(store.PREFIX + 'bad', '{invalid json')
|
|
expect(store.get('bad', { ok: true })).toEqual({ ok: true })
|
|
})
|
|
|
|
it('null 值回退默认值', () => {
|
|
localStorage.setItem(store.PREFIX + 'null-val', 'null')
|
|
expect(store.get('null-val', { default: true })).toEqual({ default: true })
|
|
})
|
|
|
|
it('空字符串回退默认值', () => {
|
|
localStorage.setItem(store.PREFIX + 'empty', '')
|
|
expect(store.get('empty', { default: true })).toEqual({ default: true })
|
|
})
|
|
})
|
|
|
|
// ==================== 类型安全 ====================
|
|
describe('类型安全', () => {
|
|
it('存储数组类型正确', () => {
|
|
store.set('arr', [1, 2, 3])
|
|
expect(Array.isArray(store.get('arr', []))).toBe(true)
|
|
})
|
|
|
|
it('存储嵌套对象类型正确', () => {
|
|
store.set('nested', { a: { b: { c: 1 } } })
|
|
expect(store.get('nested', {}).a.b.c).toBe(1)
|
|
})
|
|
})
|
|
})
|