diff --git a/cli/tests/testdata/websocketstream_test.ts b/cli/tests/testdata/websocketstream_test.ts index aa809ba16d..ba5c281ebe 100644 --- a/cli/tests/testdata/websocketstream_test.ts +++ b/cli/tests/testdata/websocketstream_test.ts @@ -2,8 +2,8 @@ import { assertEquals, + assertRejects, assertThrows, - assertThrowsAsync, } from "../../../test_util/std/testing/asserts.ts"; Deno.test("fragment", () => { @@ -57,12 +57,12 @@ Deno.test("echo string tls", async () => { Deno.test("websocket error", async () => { const ws = new WebSocketStream("wss://localhost:4242"); await Promise.all([ - assertThrowsAsync( + assertRejects( () => ws.connection, Deno.errors.UnexpectedEof, "tls handshake eof", ), - assertThrowsAsync( + assertRejects( () => ws.closed, Deno.errors.UnexpectedEof, "tls handshake eof", @@ -80,3 +80,17 @@ Deno.test("echo uint8array", async () => { ws.close(); await ws.closed; }); + +Deno.test("aborting immediately throws an AbortError", async () => { + const controller = new AbortController(); + const wss = new WebSocketStream("ws://localhost:4242", { + signal: controller.signal, + }); + controller.abort(); + await assertRejects( + () => wss.connection, + DOMException, + "connection was aborted", + ); + await assertRejects(() => wss.closed, DOMException, "connection was aborted"); +}); diff --git a/ext/websocket/lib.rs b/ext/websocket/lib.rs index ba626a45a4..f3d44cac71 100644 --- a/ext/websocket/lib.rs +++ b/ext/websocket/lib.rs @@ -239,6 +239,16 @@ where ); } + let cancel_resource = if let Some(cancel_rid) = args.cancel_handle { + let r = state + .borrow_mut() + .resource_table + .get::(cancel_rid)?; + Some(r) + } else { + None + }; + let unsafely_ignore_certificate_errors = state .borrow() .try_borrow::() @@ -283,13 +293,9 @@ where let client = client_async(request, socket); let (stream, response): (WsStream, Response) = - if let Some(cancel_rid) = args.cancel_handle { - let r = state - .borrow_mut() - .resource_table - .get::(cancel_rid)?; + if let Some(cancel_resource) = cancel_resource { client - .or_cancel(r.0.to_owned()) + .or_cancel(cancel_resource.0.to_owned()) .await .map_err(|_| DomExceptionAbortError::new("connection was aborted"))? } else {