fork of hey-api/openapi-ts because I need some additional things
1import { createClient } from '../client';
2
3describe('buildUrl', () => {
4 const client = createClient();
5
6 const scenarios: {
7 options: Parameters<typeof client.buildUrl>[0];
8 url: string;
9 }[] = [
10 {
11 options: {
12 url: '',
13 },
14 url: '/',
15 },
16 {
17 options: {
18 url: '/foo',
19 },
20 url: '/foo',
21 },
22 {
23 options: {
24 path: {
25 fooId: 1,
26 },
27 url: '/foo/{fooId}',
28 },
29 url: '/foo/1',
30 },
31 {
32 options: {
33 path: {
34 fooId: 1,
35 },
36 query: {
37 bar: 'baz',
38 },
39 url: '/foo/{fooId}',
40 },
41 url: '/foo/1?bar=baz',
42 },
43 ];
44
45 it.each(scenarios)('returns $url', ({ options, url }) => {
46 expect(client.buildUrl(options)).toBe(url);
47 });
48});
49
50describe('zero-length body handling', () => {
51 const client = createClient({ baseUrl: 'https://example.com' });
52
53 it('returns empty object for zero-length JSON response', async () => {
54 const mockResponse = new Response(null, {
55 headers: {
56 'Content-Length': '0',
57 'Content-Type': 'application/json',
58 },
59 status: 200,
60 });
61
62 const mockFetch = vi.fn().mockResolvedValue(mockResponse);
63
64 const result = await client.request({
65 fetch: mockFetch,
66 method: 'GET',
67 url: '/test',
68 });
69
70 expect(result.data).toEqual({});
71 });
72
73 it('returns empty object for empty JSON response without Content-Length header (status 200)', async () => {
74 // Simulates a server returning an empty body with status 200 and no Content-Length header
75 // This is the scenario described in the issue where response.json() throws
76 const mockResponse = new Response('', {
77 headers: {
78 'Content-Type': 'application/json',
79 },
80 status: 200,
81 });
82
83 const mockFetch = vi.fn().mockResolvedValue(mockResponse);
84
85 const result = await client.request({
86 fetch: mockFetch,
87 method: 'GET',
88 url: '/test',
89 });
90
91 expect(result.data).toEqual({});
92 });
93
94 it('returns empty object for empty response without Content-Length header and no Content-Type (defaults to JSON)', async () => {
95 // Tests the auto-detection behavior when no Content-Type is provided
96 const mockResponse = new Response('', {
97 status: 200,
98 });
99
100 const mockFetch = vi.fn().mockResolvedValue(mockResponse);
101
102 const result = await client.request({
103 fetch: mockFetch,
104 method: 'GET',
105 url: '/test',
106 });
107
108 // When parseAs is 'auto' and no Content-Type header exists, it should handle empty body gracefully
109 expect(result.data).toBeDefined();
110 });
111});