api.test.ts75 lines, 2.3 KB
| 1 | import { afterEach, expect, test, vi } from 'vitest' |
| 2 | import { ApiError, request, setSession } from './api' |
| 3 | import { getToasts } from './toast' |
| 4 | |
| 5 | afterEach(() => { |
| 6 | vi.unstubAllGlobals() |
| 7 | vi.useRealTimers() |
| 8 | localStorage.clear() |
| 9 | }) |
| 10 | |
| 11 | test('request sends the token and JSON, and reads JSON', async () => { |
| 12 | setSession({ token: 'abc', handle: 'alice' }) |
| 13 | const fetch = vi.fn().mockResolvedValue(Response.json({ id: 1 })) |
| 14 | vi.stubGlobal('fetch', fetch) |
| 15 | |
| 16 | expect( |
| 17 | await request('/posts', { method: 'POST', json: { body: 'hi' } }), |
| 18 | ).toEqual({ id: 1 }) |
| 19 | const [url, init] = fetch.mock.calls[0] |
| 20 | expect(url).toBe('/api/posts') |
| 21 | expect(init.headers.get('Authorization')).toBe('Bearer abc') |
| 22 | expect(init.body).toBe('{"body":"hi"}') |
| 23 | }) |
| 24 | |
| 25 | test('an error is an ApiError with what the server said', async () => { |
| 26 | const taken = Response.json( |
| 27 | { error: 'that handle is taken' }, |
| 28 | { |
| 29 | status: 409, |
| 30 | }, |
| 31 | ) |
| 32 | vi.stubGlobal('fetch', vi.fn().mockResolvedValue(taken)) |
| 33 | |
| 34 | const error: ApiError = await request<never>('/users').catch((e) => e) |
| 35 | expect(error).toBeInstanceOf(ApiError) |
| 36 | expect([error.status, error.message]).toEqual([ |
| 37 | 409, |
| 38 | 'that handle is taken', |
| 39 | ]) |
| 40 | }) |
| 41 | |
| 42 | test('a 429 waits for Retry-After, says so, and goes again', async () => { |
| 43 | vi.useFakeTimers() |
| 44 | const busy = new Response(null, { |
| 45 | status: 429, |
| 46 | headers: { 'Retry-After': '3' }, |
| 47 | }) |
| 48 | const fetch = vi |
| 49 | .fn() |
| 50 | .mockResolvedValueOnce(busy) |
| 51 | .mockResolvedValue(new Response(null, { status: 204 })) |
| 52 | vi.stubGlobal('fetch', fetch) |
| 53 | |
| 54 | const done = request('/posts/1/like', { method: 'POST' }) |
| 55 | await vi.advanceTimersByTimeAsync(2900) |
| 56 | expect(fetch).toHaveBeenCalledTimes(1) |
| 57 | expect(getToasts().map((t) => t.text)).toEqual([ |
| 58 | 'Busy moment. Trying again in 3s.', |
| 59 | ]) |
| 60 | await vi.advanceTimersByTimeAsync(100) |
| 61 | await done |
| 62 | expect(fetch).toHaveBeenCalledTimes(2) |
| 63 | }) |
| 64 | |
| 65 | test('after two waits, a 429 is an error the screen shows', async () => { |
| 66 | vi.useFakeTimers() |
| 67 | const busy = () => new Response(null, { status: 429 }) |
| 68 | const fetch = vi.fn(async () => busy()) |
| 69 | vi.stubGlobal('fetch', fetch) |
| 70 | |
| 71 | const done = request<never>('/feed').catch((e: ApiError) => e.status) |
| 72 | await vi.advanceTimersByTimeAsync(2000) // two waits of a second |
| 73 | expect(await done).toBe(429) |
| 74 | expect(fetch).toHaveBeenCalledTimes(3) |
| 75 | }) |