websocket-bridge-outbounds.test.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  2. import { renderHook } from '@testing-library/react';
  3. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  4. import type { ReactNode } from 'react';
  5. import { getSharedWebSocketClient } from '@/api/websocket';
  6. import { useWebSocketBridge } from '@/api/websocketBridge';
  7. import { keys } from '@/api/queryKeys';
  8. type ListenerMap = { listeners: Map<string, Set<(payload: unknown) => void>> };
  9. describe('websocket bridge outbounds handler', () => {
  10. let originalWS: typeof WebSocket;
  11. beforeEach(() => {
  12. originalWS = globalThis.WebSocket;
  13. class FakeWebSocket {
  14. static readonly CONNECTING = 0;
  15. static readonly OPEN = 1;
  16. static readonly CLOSING = 2;
  17. static readonly CLOSED = 3;
  18. readyState = FakeWebSocket.CONNECTING;
  19. addEventListener() {}
  20. removeEventListener() {}
  21. close() {}
  22. send() {}
  23. }
  24. globalThis.WebSocket = FakeWebSocket as unknown as typeof WebSocket;
  25. });
  26. afterEach(() => {
  27. globalThis.WebSocket = originalWS;
  28. });
  29. it('ignores a non-array outbounds push instead of poisoning the cache', () => {
  30. const queryClient = new QueryClient();
  31. const wrapper = ({ children }: { children: ReactNode }) => (
  32. <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  33. );
  34. renderHook(() => useWebSocketBridge(), { wrapper });
  35. const client = getSharedWebSocketClient() as unknown as ListenerMap;
  36. const handlers = client.listeners.get('outbounds');
  37. expect(handlers && handlers.size).toBeGreaterThan(0);
  38. for (const handler of handlers ?? []) handler({ not: 'an array' });
  39. expect(queryClient.getQueryData(keys.xray.outboundsTraffic())).toBeUndefined();
  40. });
  41. });