forked from Lilly-Protocol/lily-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode-http.test.ts
More file actions
83 lines (77 loc) · 2.84 KB
/
Copy pathnode-http.test.ts
File metadata and controls
83 lines (77 loc) · 2.84 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { describe, it, expect, afterAll, beforeAll } from 'vitest';
import http from 'node:http';
import { createFetchHttpClient } from '../../src/http/fetch-http-client';
import { resolveLilySdkConfig } from '../../src/config/resolve-config';
describe('Transport against node:http (issue #104)', () => {
let server: http.Server;
let baseUrl: string;
beforeAll(() => {
return new Promise<void>((resolve) => {
server = http.createServer((req, res) => {
if (req.url === '/v1/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
return;
}
if (req.url?.startsWith('/v1/items/')) {
const id = req.url.split('/').pop();
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id, name: `item-${id}` }));
return;
}
}
if (req.url === '/v1/echo' && req.method === 'POST') {
let body = '';
req.on('data', (chunk) => (body += chunk));
req.on('end', () => {
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(body || '{}');
});
return;
}
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'not found' }));
});
server.listen(0, '127.0.0.1', () => {
const addr = server.address();
if (addr && typeof addr !== 'string') {
baseUrl = `http://127.0.0.1:${addr.port}`;
}
resolve();
});
});
});
afterAll(() => {
return new Promise<void>((resolve) => server.close(() => resolve()));
});
it('makes GET request and parses JSON response', async () => {
const config = resolveLilySdkConfig({ baseUrl, fetch: globalThis.fetch });
const client = createFetchHttpClient(config);
const res = await client.request({ method: 'GET', path: '/v1/health' });
expect(res.status).toBe(200);
expect(res.data).toEqual({ status: 'ok' });
});
it('makes POST request with body', async () => {
const config = resolveLilySdkConfig({ baseUrl, fetch: globalThis.fetch });
const client = createFetchHttpClient(config);
const res = await client.request({
method: 'POST',
path: '/v1/echo',
body: { message: 'hello' },
});
expect(res.status).toBe(201);
expect(res.data).toEqual({ message: 'hello' });
});
it('handles 404 response', async () => {
const config = resolveLilySdkConfig({
baseUrl,
fetch: globalThis.fetch,
retry: { retries: 0, retryDelayMs: 0, retryableStatusCodes: [] },
});
const client = createFetchHttpClient(config);
await expect(
client.request({ method: 'GET', path: '/v1/unknown' }),
).rejects.toThrow();
});
});