gongxiangp2/lib/__tests__/upload-sessions-redis-errors.test.ts

59 lines
1.7 KiB
TypeScript

/** @jest-environment node */
jest.mock('ioredis', () => {
const client = {
get: jest.fn(),
exists: jest.fn(),
expire: jest.fn(),
on: jest.fn(),
}
const RedisMock = jest.fn(() => client)
;(RedisMock as any).__client = client
return RedisMock
})
import Redis from 'ioredis'
import {
getUploadSession,
hasUploadSession,
refreshUploadSession,
} from '@/lib/upload-sessions-redis'
const redisClient = (Redis as unknown as {
__client: {
get: jest.Mock
exists: jest.Mock
expire: jest.Mock
}
}).__client
describe('upload-sessions Redis adapter error semantics', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('Redis 成功返回 nil/0 时才表示会话不存在', async () => {
redisClient.get.mockResolvedValueOnce(null)
redisClient.exists.mockResolvedValueOnce(0)
redisClient.expire.mockResolvedValueOnce(0)
await expect(getUploadSession('upload-missing')).resolves.toBeNull()
await expect(hasUploadSession('upload-missing')).resolves.toBe(false)
await expect(refreshUploadSession('upload-missing')).resolves.toBe(false)
})
test.each([
['get', getUploadSession],
['exists', hasUploadSession],
['expire', refreshUploadSession],
] as const)('%s 命令异常时向上抛出,而不是伪装成不存在', async (method, action) => {
redisClient[method].mockRejectedValueOnce(new Error('redis unavailable'))
await expect(action('upload-active')).rejects.toThrow('redis unavailable')
})
test('损坏的 Redis 会话 JSON 也不会被当成不存在', async () => {
redisClient.get.mockResolvedValueOnce('{broken-json')
await expect(getUploadSession('upload-corrupted')).rejects.toThrow()
})
})