|
| 1 | +import React from 'react'; |
| 2 | +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; |
| 3 | +import { render, screen, act, waitFor, renderHook } from '@testing-library/react'; |
| 4 | +import { HttpConsoleProvider, useHttpConsole } from '../../contexts/HttpConsoleContext'; |
| 5 | +import { LanguageProvider } from '../../contexts/LanguageContext'; |
| 6 | + |
| 7 | +// Mock HttpConsoleDock to avoid rendering it |
| 8 | +vi.mock('../../features/wallet/components/ConsoleView', () => ({ |
| 9 | + ConsoleView: () => <div>ConsoleView</div>, |
| 10 | + HttpConsoleDock: () => <div>Dock</div> |
| 11 | +})); |
| 12 | + |
| 13 | +// Test component to access context |
| 14 | +const TestComponent = () => { |
| 15 | + const { setEnabled, events, clear } = useHttpConsole(); |
| 16 | + return ( |
| 17 | + <div> |
| 18 | + <button onClick={() => setEnabled(true)}>Enable</button> |
| 19 | + <button onClick={clear}>Clear</button> |
| 20 | + <div data-testid="count">{events.length}</div> |
| 21 | + <div data-testid="last-method">{events[0]?.method}</div> |
| 22 | + <div data-testid="last-url">{events[0]?.url}</div> |
| 23 | + </div> |
| 24 | + ); |
| 25 | +}; |
| 26 | + |
| 27 | +describe('HttpConsoleContext Patching', () => { |
| 28 | + let originalFetch: any; |
| 29 | + let originalXhr: any; |
| 30 | + |
| 31 | + // Mock XHR class |
| 32 | + class MockXHR { |
| 33 | + addEventListener = vi.fn(); |
| 34 | + setRequestHeader = vi.fn(); |
| 35 | + status = 200; |
| 36 | + responseText = '{"mock": "xhr"}'; |
| 37 | + } |
| 38 | + |
| 39 | + let originalProtoOpen: any; |
| 40 | + |
| 41 | + beforeEach(() => { |
| 42 | + originalFetch = window.fetch; |
| 43 | + originalXhr = window.XMLHttpRequest; |
| 44 | + |
| 45 | + // Define prototype methods (MockXHR instance methods) |
| 46 | + (MockXHR.prototype as any).open = vi.fn(); |
| 47 | + (MockXHR.prototype as any).send = vi.fn(); |
| 48 | + // Mimic addEventListener as well if patched? No, only open/send patched. |
| 49 | + |
| 50 | + window.XMLHttpRequest = MockXHR as any; |
| 51 | + originalProtoOpen = (MockXHR.prototype as any).open; |
| 52 | + |
| 53 | + // However, HttpConsoleContext patches XMLHttpRequest.prototype. |
| 54 | + // If I replace window.XMLHttpRequest with a class that doesn't have the same prototype chain behavior |
| 55 | + // as the one HttpConsoleContext expects (it patches XMLHttpRequest.prototype directly), it might fail. |
| 56 | + // HttpConsoleContext does: const proto = XMLHttpRequest.prototype; |
| 57 | + |
| 58 | + // If I say window.XMLHttpRequest = MockXHR, then XMLHttpRequest.prototype is MockXHR.prototype. |
| 59 | + // So HttpConsoleContext will patch MockXHR.prototype. |
| 60 | + // Then when TestComponent creates new XMLHttpRequest(), it gets new MockXHR(). |
| 61 | + // Its 'open' method will be the PATCHED one. |
| 62 | + // The patched one calls 'origXhrOpenRef' which is 'MockXHR.prototype.open'. |
| 63 | + // So I need MockXHR.prototype.open to be a function. |
| 64 | + // Class methods are on prototype. |
| 65 | + }); |
| 66 | + |
| 67 | + afterEach(() => { |
| 68 | + window.fetch = originalFetch; |
| 69 | + window.XMLHttpRequest = originalXhr; |
| 70 | + vi.restoreAllMocks(); |
| 71 | + }); |
| 72 | + |
| 73 | + it('should patch fetch and capture requests when enabled', async () => { |
| 74 | + const mockFetch = vi.fn().mockResolvedValue(new Response('{"json":true}')); |
| 75 | + window.fetch = mockFetch; |
| 76 | + |
| 77 | + render( |
| 78 | + <LanguageProvider> |
| 79 | + <HttpConsoleProvider> |
| 80 | + <TestComponent /> |
| 81 | + </HttpConsoleProvider> |
| 82 | + </LanguageProvider> |
| 83 | + ); |
| 84 | + |
| 85 | + // Enable console |
| 86 | + await act(async () => { |
| 87 | + screen.getByText('Enable').click(); |
| 88 | + }); |
| 89 | + |
| 90 | + // Current fetch should be patched |
| 91 | + expect(window.fetch).not.toBe(originalFetch); |
| 92 | + |
| 93 | + // Perform a fetch |
| 94 | + await act(async () => { |
| 95 | + await window.fetch('https://api.example.com/data', { |
| 96 | + method: 'POST', |
| 97 | + body: JSON.stringify({ method: 'eth_chainId', params: [] }) |
| 98 | + }); |
| 99 | + }); |
| 100 | + |
| 101 | + // Verify underlying fetch called |
| 102 | + expect(mockFetch).toHaveBeenCalled(); |
| 103 | + |
| 104 | + // Verify event captured |
| 105 | + expect(screen.getByTestId('count')).toHaveTextContent('1'); |
| 106 | + expect(screen.getByTestId('last-method')).toHaveTextContent('POST'); |
| 107 | + expect(screen.getByTestId('last-url')).toHaveTextContent('https://api.example.com/data'); |
| 108 | + }); |
| 109 | + |
| 110 | + it('should patch XMLHttpRequest and capture requests when enabled', async () => { |
| 111 | + render( |
| 112 | + <LanguageProvider> |
| 113 | + <HttpConsoleProvider> |
| 114 | + <TestComponent /> |
| 115 | + </HttpConsoleProvider> |
| 116 | + </LanguageProvider> |
| 117 | + ); |
| 118 | + |
| 119 | + await act(async () => { |
| 120 | + screen.getByText('Enable').click(); |
| 121 | + }); |
| 122 | + |
| 123 | + // Create XHR |
| 124 | + const xhr = new XMLHttpRequest(); |
| 125 | + vi.spyOn(xhr, 'addEventListener'); // Spy to check if loadend attached (internal detail) |
| 126 | + |
| 127 | + await act(async () => { |
| 128 | + xhr.open('GET', 'https://xhr.example.com'); |
| 129 | + xhr.send(); |
| 130 | + |
| 131 | + // Find the 'loadend' listener |
| 132 | + // addEventListener(type, listener, options) |
| 133 | + const call = (xhr.addEventListener as any).mock.calls.find((c: any) => c[0] === 'loadend'); |
| 134 | + if (call) { |
| 135 | + const listener = call[1]; |
| 136 | + if (typeof listener === 'function') { // EventListener or EventListenerObject |
| 137 | + listener(new Event('loadend')); |
| 138 | + } else if (listener && typeof listener.handleEvent === 'function') { |
| 139 | + listener.handleEvent(new Event('loadend')); |
| 140 | + } |
| 141 | + } |
| 142 | + }); |
| 143 | + |
| 144 | + expect(screen.getByTestId('count')).toHaveTextContent('1'); |
| 145 | + expect(screen.getByTestId('last-url')).toHaveTextContent('https://xhr.example.com'); |
| 146 | + }); |
| 147 | + |
| 148 | + it('should restore original fetch and XHR on unmount', async () => { |
| 149 | + const { unmount } = render( |
| 150 | + <LanguageProvider> |
| 151 | + <HttpConsoleProvider> |
| 152 | + <TestComponent /> |
| 153 | + </HttpConsoleProvider> |
| 154 | + </LanguageProvider> |
| 155 | + ); |
| 156 | + |
| 157 | + await act(async () => { |
| 158 | + screen.getByText('Enable').click(); |
| 159 | + }); |
| 160 | + |
| 161 | + expect(window.fetch).not.toBe(originalFetch); |
| 162 | + unmount(); |
| 163 | + // Fetch is bound so identity might differ, but checking XHR prototype |
| 164 | + expect(XMLHttpRequest.prototype.open).toBe(originalProtoOpen); |
| 165 | + }); |
| 166 | + |
| 167 | + it('should handle RPC batch requests correctly', async () => { |
| 168 | + const mockFetch = vi.fn().mockResolvedValue(new Response('[{"id":1, "result":"0x1"}, {"id":2, "result":"0x2"}]')); |
| 169 | + window.fetch = mockFetch; |
| 170 | + |
| 171 | + render( |
| 172 | + <LanguageProvider> |
| 173 | + <HttpConsoleProvider> |
| 174 | + <TestComponent /> |
| 175 | + </HttpConsoleProvider> |
| 176 | + </LanguageProvider> |
| 177 | + ); |
| 178 | + |
| 179 | + await act(async () => { |
| 180 | + screen.getByText('Enable').click(); |
| 181 | + }); |
| 182 | + |
| 183 | + await act(async () => { |
| 184 | + await window.fetch('https://rpc.example.com', { |
| 185 | + method: 'POST', |
| 186 | + body: JSON.stringify([ |
| 187 | + { method: 'eth_blockNumber', id: 1 }, |
| 188 | + { method: 'eth_gasPrice', id: 2 } |
| 189 | + ]) |
| 190 | + }); |
| 191 | + }); |
| 192 | + |
| 193 | + // Should produce 2 events (one for each batch item) |
| 194 | + // pushEvent prepends, so we expect 2 events. |
| 195 | + // Wait, logic: for (i=batchSize-1; i>=0; i--) pushEvent(...). |
| 196 | + // It pushes them in reverse order to the events array? |
| 197 | + // pushEvent uses `setEvents(prev => [ev, ...prev])`. |
| 198 | + // If I push 1 then 0. |
| 199 | + // Events = [0, 1]. |
| 200 | + expect(await screen.findByTestId('count')).toHaveTextContent('2'); |
| 201 | + }); |
| 202 | + |
| 203 | + it('should handle fetch errors gracefully', async () => { |
| 204 | + const mockFetch = vi.fn().mockRejectedValue(new Error('Network Error')); |
| 205 | + window.fetch = mockFetch; |
| 206 | + |
| 207 | + render( |
| 208 | + <LanguageProvider> |
| 209 | + <HttpConsoleProvider> |
| 210 | + <TestComponent /> |
| 211 | + </HttpConsoleProvider> |
| 212 | + </LanguageProvider> |
| 213 | + ); |
| 214 | + |
| 215 | + await act(async () => { |
| 216 | + screen.getByText('Enable').click(); |
| 217 | + }); |
| 218 | + |
| 219 | + await expect(window.fetch('https://fail.com')).rejects.toThrow('Network Error'); |
| 220 | + |
| 221 | + await waitFor(() => { |
| 222 | + expect(screen.getByTestId('count')).toHaveTextContent('1'); |
| 223 | + }); |
| 224 | + }); |
| 225 | +}); |
0 commit comments