diff --git a/cli/tests/unit/fetch_test.ts b/cli/tests/unit/fetch_test.ts index 9776baa2fb..71307cd69d 100644 --- a/cli/tests/unit/fetch_test.ts +++ b/cli/tests/unit/fetch_test.ts @@ -5,6 +5,7 @@ import { assertThrows, assertThrowsAsync, fail, + unimplemented, unitTest, } from "./test_util.ts"; @@ -20,12 +21,37 @@ unitTest({ perms: { net: true } }, async function fetchProtocolError(): Promise< ); }); +function findClosedPortInRange( + minPort: number, + maxPort: number, +): number | never { + let port = minPort; + + // If we hit the return statement of this loop + // that means that we did not throw an + // AddrInUse error when we executed Deno.listen. + while (port < maxPort) { + try { + const listener = Deno.listen({ port }); + listener.close(); + return port; + } catch (e) { + port++; + } + } + + unimplemented( + `No available ports between ${minPort} and ${maxPort} to test fetch`, + ); +} + unitTest( { perms: { net: true } }, async function fetchConnectionError(): Promise { + const port = findClosedPortInRange(4000, 9999); await assertThrowsAsync( async (): Promise => { - await fetch("http://localhost:4000"); + await fetch(`http://localhost:${port}`); }, TypeError, "error trying to connect", diff --git a/cli/tests/unit/test_util.ts b/cli/tests/unit/test_util.ts index 6c3c0c6a06..e6adc6583c 100644 --- a/cli/tests/unit/test_util.ts +++ b/cli/tests/unit/test_util.ts @@ -17,6 +17,7 @@ export { assertThrows, assertThrowsAsync, fail, + unimplemented, unreachable, } from "../../../test_util/std/testing/asserts.ts"; export { deferred } from "../../../test_util/std/async/deferred.ts";