-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.test.ts
More file actions
37 lines (32 loc) · 1.83 KB
/
Copy pathapi.test.ts
File metadata and controls
37 lines (32 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { describe, expect, it, vi } from 'vitest';
import { ApiError, fetchMe } from '../src/lib/api';
import type { StoredSession } from '../src/lib/session';
const SESSION: StoredSession = { accessToken: 'access-123', idToken: 'id-456', expiresAt: Date.now() + 1000 };
const ME_BODY = { userId: 'u1', email: 'user@example.com', created: false, plan: 'free', status: 'active', forcedDryRun: true };
describe('fetchMe', () => {
it('sends the ID token as the bearer, not the access token', async () => {
const fetchMock = vi.fn(async (_url: string, init: RequestInit) => {
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer id-456');
return new Response(JSON.stringify(ME_BODY), { status: 200 });
});
await fetchMe('https://api.example.com', SESSION, fetchMock as unknown as typeof fetch);
expect(fetchMock).toHaveBeenCalledWith('https://api.example.com/me', expect.anything());
});
it('returns the parsed body on success', async () => {
const fetchMock = vi.fn(async () => new Response(JSON.stringify(ME_BODY), { status: 200 }));
const me = await fetchMe('https://api.example.com', SESSION, fetchMock as unknown as typeof fetch);
expect(me).toEqual(ME_BODY);
});
it('fails closed with the status code on a non-2xx response', async () => {
const fetchMock = vi.fn(async () => new Response('unauthenticated', { status: 401 }));
await expect(fetchMe('https://api.example.com', SESSION, fetchMock as unknown as typeof fetch)).rejects.toMatchObject({
status: 401,
});
});
it('rejects with ApiError specifically, not a generic Error', async () => {
const fetchMock = vi.fn(async () => new Response('', { status: 500 }));
await expect(fetchMe('https://api.example.com', SESSION, fetchMock as unknown as typeof fetch)).rejects.toBeInstanceOf(
ApiError,
);
});
});