|
| 1 | +import { describe, it, expect, vi } from 'vitest' |
| 2 | +import { usePromise } from '../src' |
| 3 | + |
| 4 | +function delay(ms: number) { |
| 5 | + return new Promise(resolve => setTimeout(resolve, ms)) |
| 6 | +} |
| 7 | + |
| 8 | +describe('usePromise', () => { |
| 9 | + it('resolves successfully', async () => { |
| 10 | + const { state, execute } = usePromise(async () => 'hello') |
| 11 | + |
| 12 | + await execute() |
| 13 | + |
| 14 | + expect(state.value.status).toBe('success') |
| 15 | + expect(state.value.data).toBe('hello') |
| 16 | + }) |
| 17 | + |
| 18 | + it('handles errors', async () => { |
| 19 | + const { state, execute } = usePromise(async () => { |
| 20 | + throw new Error('fail') |
| 21 | + }) |
| 22 | + |
| 23 | + await execute() |
| 24 | + |
| 25 | + expect(state.value.status).toBe('error') |
| 26 | + expect(state.value.error?.message).toBe('fail') |
| 27 | + }) |
| 28 | + |
| 29 | + it('preserves data during reload', async () => { |
| 30 | + let count = 0 |
| 31 | + |
| 32 | + const { state, execute } = usePromise(async () => { |
| 33 | + count++ |
| 34 | + await delay(10) |
| 35 | + return count |
| 36 | + }) |
| 37 | + |
| 38 | + await execute() |
| 39 | + const first = state.value.data |
| 40 | + |
| 41 | + execute() // don't await |
| 42 | + |
| 43 | + expect(state.value.data).toBe(first) |
| 44 | + }) |
| 45 | + |
| 46 | + it('aborts previous request', async () => { |
| 47 | + const spy = vi.fn() |
| 48 | + |
| 49 | + const { execute } = usePromise(async (signal) => { |
| 50 | + await delay(20) |
| 51 | + if (!signal.aborted) spy() |
| 52 | + }) |
| 53 | + |
| 54 | + execute() |
| 55 | + execute() |
| 56 | + |
| 57 | + await delay(50) |
| 58 | + |
| 59 | + expect(spy).toHaveBeenCalledTimes(1) |
| 60 | + }) |
| 61 | + |
| 62 | + it('prevents race conditions', async () => { |
| 63 | + const { state, execute } = usePromise( |
| 64 | + async (_, value: number) => { |
| 65 | + await delay(value === 1 ? 30 : 10) |
| 66 | + return value |
| 67 | + }, |
| 68 | + ) |
| 69 | + |
| 70 | + execute(1) |
| 71 | + await execute(2) |
| 72 | + |
| 73 | + expect(state.value.data).toBe(2) |
| 74 | + }) |
| 75 | + |
| 76 | + it('abort prevents state update', async () => { |
| 77 | + const { state, execute, abort } = usePromise(async () => { |
| 78 | + await delay(20) |
| 79 | + return 'done' |
| 80 | + }) |
| 81 | + |
| 82 | + execute() |
| 83 | + abort() |
| 84 | + |
| 85 | + await delay(30) |
| 86 | + |
| 87 | + expect(state.value.status).not.toBe('success') |
| 88 | + }) |
| 89 | +}) |
0 commit comments