1
0

api-client.test.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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({ ...base, method: 'POST', path: '/panel/api/inbounds/add', body: '{"up":0}' });
  37. expect(cmd).toContain('-X POST');
  38. expect(cmd).toContain("--data '{\"up\":0}'");
  39. expect(cmd).toContain("Content-Type: application/json");
  40. });
  41. it('POST without a body omits --data', () => {
  42. const cmd = buildCurl({ ...base, method: 'POST', path: '/panel/api/inbounds/resetAllTraffics' });
  43. expect(cmd).not.toContain('--data');
  44. });
  45. });
  46. describe('buildFetchSnippet', () => {
  47. it('GET sets method + Authorization and no body', () => {
  48. const snip = buildFetchSnippet({ ...base, method: 'GET' });
  49. expect(snip).toContain("method: 'GET'");
  50. expect(snip).toContain("'Authorization': 'Bearer TKN'");
  51. expect(snip).not.toContain('body:');
  52. });
  53. it('POST with a body includes a JSON.stringify body', () => {
  54. const snip = buildFetchSnippet({ ...base, method: 'POST', path: '/panel/api/inbounds/add', body: '{"up":0}' });
  55. expect(snip).toContain("method: 'POST'");
  56. expect(snip).toContain('body: JSON.stringify(');
  57. });
  58. });