diff --git a/testing/asserts.ts b/testing/asserts.ts index d46b26dedbf3..55c647d0499a 100644 --- a/testing/asserts.ts +++ b/testing/asserts.ts @@ -329,6 +329,23 @@ export function assertNotStrictEquals( ); } +/** + * Make an assertion that actual is not null or undefined. If not + * then thrown. + */ +export function assertExists( + actual: unknown, + msg?: string, +): void { + if (actual === undefined || actual === null) { + if (!msg) { + msg = + `actual: "${actual}" expected to match anything but null or undefined`; + } + throw new AssertionError(msg); + } +} + /** * Make an assertion that actual includes expected. If not * then thrown. diff --git a/testing/asserts_test.ts b/testing/asserts_test.ts index d357a761beb3..4f153e78c6b6 100644 --- a/testing/asserts_test.ts +++ b/testing/asserts_test.ts @@ -4,6 +4,7 @@ import { assert, assertArrayIncludes, assertEquals, + assertExists, AssertionError, assertMatch, assertNotEquals, @@ -160,6 +161,34 @@ Deno.test("testingNotEquals", function (): void { assertEquals(didThrow, true); }); +Deno.test("testingAssertExists", function (): void { + assertExists("Denosaurus"); + assertExists(false); + assertExists(0); + assertExists(""); + assertExists(-0); + assertExists(0); + assertExists(NaN); + let didThrow; + try { + assertExists(undefined); + didThrow = false; + } catch (e) { + assert(e instanceof AssertionError); + didThrow = true; + } + assertEquals(didThrow, true); + didThrow = false; + try { + assertExists(null); + didThrow = false; + } catch (e) { + assert(e instanceof AssertionError); + didThrow = true; + } + assertEquals(didThrow, true); +}); + Deno.test("testingAssertStringContains", function (): void { assertStringIncludes("Denosaurus", "saur"); assertStringIncludes("Denosaurus", "Deno");