1
0

api-client.test.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { describe, it, expect } from 'vitest';
  2. import { normalizeBase, joinUrl, buildCurl, buildFetchSnippet } from './api-client';
  3. describe('normalizeBase', () => {
  4. it('strips a trailing slash', () => {
  5. expect(normalizeBase('https://panel.example.com:2053/')).toBe('https://panel.example.com:2053');
  6. });
  7. it('leaves a clean base unchanged', () => {
  8. expect(normalizeBase('https://panel.example.com:2053')).toBe('https://panel.example.com:2053');
  9. });
  10. });
  11. describe('joinUrl', () => {
  12. it('joins with exactly one slash regardless of input slashes', () => {
  13. expect(joinUrl('https://x.com/', 'panel/api/inbounds/list')).toBe(
  14. 'https://x.com/panel/api/inbounds/list',
  15. );
  16. expect(joinUrl('https://x.com', '/panel/api/inbounds/list')).toBe(
  17. 'https://x.com/panel/api/inbounds/list',
  18. );
  19. });
  20. });
  21. const base = {
  22. baseUrl: 'https://panel.example.com:2053',
  23. token: 'TKN',
  24. path: '/panel/api/inbounds/list',
  25. };
  26. describe('buildCurl', () => {
  27. it('GET emits the Bearer header, a single-quoted URL, and no body flag', () => {
  28. const cmd = buildCurl({ ...base, method: 'GET' });
  29. expect(cmd).toContain('-X GET');
  30. expect(cmd).toContain("-H 'Authorization: Bearer TKN'");
  31. expect(cmd).toContain("'https://panel.example.com:2053/panel/api/inbounds/list'");
  32. expect(cmd).not.toContain('--data');
  33. expect(cmd).not.toContain('-d ');
  34. });
  35. it('POST with a body emits --data and a JSON content type', () => {
  36. const cmd = buildCurl({
  37. ...base,
  38. method: 'POST',
  39. path: '/panel/api/inbounds/add',
  40. body: '{"up":0}',
  41. });
  42. expect(cmd).toContain('-X POST');
  43. expect(cmd).toContain('--data \'{"up":0}\'');
  44. expect(cmd).toContain('Content-Type: application/json');
  45. });
  46. it('POST without a body omits --data', () => {
  47. const cmd = buildCurl({
  48. ...base,
  49. method: 'POST',
  50. path: '/panel/api/inbounds/resetAllTraffics',
  51. });
  52. expect(cmd).not.toContain('--data');
  53. });
  54. });
  55. describe('buildFetchSnippet', () => {
  56. it('GET sets method + Authorization and no body', () => {
  57. const snip = buildFetchSnippet({ ...base, method: 'GET' });
  58. expect(snip).toContain("method: 'GET'");
  59. expect(snip).toContain("'Authorization': 'Bearer TKN'");
  60. expect(snip).not.toContain('body:');
  61. });
  62. it('POST with a body includes a JSON.stringify body', () => {
  63. const snip = buildFetchSnippet({
  64. ...base,
  65. method: 'POST',
  66. path: '/panel/api/inbounds/add',
  67. body: '{"up":0}',
  68. });
  69. expect(snip).toContain("method: 'POST'");
  70. expect(snip).toContain('body: JSON.stringify(');
  71. });
  72. });