|
1 | 1 | import { HTTPTransport, HTTPTransportOptions } from "./HTTPTransport.js"; |
2 | 2 | import * as reqMocks from "../__mocks__/requestData.js"; |
| 3 | +import { AbortError } from "../Error.js"; |
3 | 4 |
|
4 | 5 | describe("HTTPTransport", () => { |
5 | 6 | let mockFetch: jest.MockedFunction<typeof fetch>; |
@@ -179,4 +180,56 @@ describe("HTTPTransport", () => { |
179 | 180 | expect(injectedFetchMock.mock.calls.length).toEqual(1); |
180 | 181 | expect(result).toEqual(undefined); |
181 | 182 | }); |
| 183 | + |
| 184 | + it("should use global fetch if no fetcher provided", async () => { |
| 185 | + const globalFetch = jest.fn().mockImplementation((url, options) => { |
| 186 | + const body = options?.body as string; |
| 187 | + const responseText = reqMocks.generateMockResponseData(url.toString(), body); |
| 188 | + return Promise.resolve({ |
| 189 | + text: () => Promise.resolve(responseText), |
| 190 | + }); |
| 191 | + }) as any; |
| 192 | + global.fetch = globalFetch; |
| 193 | + |
| 194 | + const httpTransport = new HTTPTransport("http://localhost:8545/rpc-request"); |
| 195 | + await httpTransport.sendData({ |
| 196 | + request: reqMocks.generateMockRequest(1, "foo", ["bar"]), |
| 197 | + internalID: 1, |
| 198 | + }); |
| 199 | + |
| 200 | + expect(globalFetch).toHaveBeenCalled(); |
| 201 | + }); |
| 202 | + |
| 203 | + it("should abort the fetch request when signal is aborted", async () => { |
| 204 | + const controller = new AbortController(); |
| 205 | + const httpTransport = new HTTPTransport("http://localhost:8545", { |
| 206 | + fetcher: mockFetch, |
| 207 | + }); |
| 208 | + const data = reqMocks.generateMockRequest(1, "foo", ["bar"]); |
| 209 | + |
| 210 | + // Setup mock to fail if aborted (simulating fetch behavior) |
| 211 | + mockFetch.mockImplementation(async (_url, options) => { |
| 212 | + if (options?.signal?.aborted) { |
| 213 | + throw new DOMException("The user aborted a request.", "AbortError"); |
| 214 | + } |
| 215 | + return new Promise((_, reject) => { |
| 216 | + options?.signal?.addEventListener("abort", () => { |
| 217 | + reject(new DOMException("The user aborted a request.", "AbortError")); |
| 218 | + }); |
| 219 | + }); |
| 220 | + }); |
| 221 | + |
| 222 | + const prom = httpTransport.sendData({ |
| 223 | + request: data, |
| 224 | + internalID: 1, |
| 225 | + }, null, controller.signal); |
| 226 | + |
| 227 | + controller.abort(); |
| 228 | + |
| 229 | + await expect(prom).rejects.toThrow(AbortError); |
| 230 | + |
| 231 | + const callArgs = mockFetch.mock.calls[0]; |
| 232 | + expect(callArgs[1]?.signal).toBeDefined(); |
| 233 | + expect(callArgs[1]?.signal?.aborted).toBe(true); |
| 234 | + }); |
182 | 235 | }); |
0 commit comments