Assertions

To help developers write tests the Deno standard library comes with a built-in assertions module which can be imported from https://deno.land/std@$STD_VERSION/testing/asserts.ts.

  1. import { assert } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts";
  2. Deno.test("Hello Test", () => {
  3. assert("Hello");
  4. });

⚠️ Some popular assertion libraries, like Chai, can be used in Deno too, for example usage see https://deno.land/std@$STD_VERSION/testing/chai_example.ts.

The assertions module provides 14 assertions:

  • assert(expr: unknown, msg = ""): asserts expr
  • assertEquals(actual: unknown, expected: unknown, msg?: string): void
  • assertExists(actual: unknown,msg?: string): void
  • assertNotEquals(actual: unknown, expected: unknown, msg?: string): void
  • assertStrictEquals(actual: unknown, expected: unknown, msg?: string): void
  • assertAlmostEquals(actual: number, expected: number, epsilon = 1e-7, msg?: string): void
  • assertInstanceOf(actual: unknown, expectedType: unknown, msg?: string): void
  • assertStringIncludes(actual: string, expected: string, msg?: string): void
  • assertArrayIncludes(actual: unknown[], expected: unknown[], msg?: string): void
  • assertMatch(actual: string, expected: RegExp, msg?: string): void
  • assertNotMatch(actual: string, expected: RegExp, msg?: string): void
  • assertObjectMatch( actual: Record<PropertyKey, unknown>, expected: Record<PropertyKey, unknown>): void
  • assertThrows(fn: () => void, ErrorClass?: Constructor, msgIncludes?: string | undefined, msg?: string | undefined): Error
  • assertRejects(fn: () => Promise<unknown>, ErrorClass?: Constructor, msgIncludes?: string | undefined, msg?: string | undefined): Promise<void>

Assert

The assert method is a simple ‘truthy’ assertion and can be used to assert any value which can be inferred as true.

  1. Deno.test("Test Assert", () => {
  2. assert(1);
  3. assert("Hello");
  4. assert(true);
  5. });

Exists

The assertExists can be used to check if a value is not null or undefined.

  1. assertExists("Denosaurus");
  2. Deno.test("Test Assert Exists", () => {
  3. assertExists("Denosaurus");
  4. assertExists(false);
  5. assertExists(0);
  6. });

Equality

There are three equality assertions available, assertEquals(), assertNotEquals() and assertStrictEquals().

The assertEquals() and assertNotEquals() methods provide a general equality check and are capable of asserting equality between primitive types and objects.

  1. Deno.test("Test Assert Equals", () => {
  2. assertEquals(1, 1);
  3. assertEquals("Hello", "Hello");
  4. assertEquals(true, true);
  5. assertEquals(undefined, undefined);
  6. assertEquals(null, null);
  7. assertEquals(new Date(), new Date());
  8. assertEquals(new RegExp("abc"), new RegExp("abc"));
  9. class Foo {}
  10. const foo1 = new Foo();
  11. const foo2 = new Foo();
  12. assertEquals(foo1, foo2);
  13. });
  14. Deno.test("Test Assert Not Equals", () => {
  15. assertNotEquals(1, 2);
  16. assertNotEquals("Hello", "World");
  17. assertNotEquals(true, false);
  18. assertNotEquals(undefined, "");
  19. assertNotEquals(new Date(), Date.now());
  20. assertNotEquals(new RegExp("abc"), new RegExp("def"));
  21. });

By contrast assertStrictEquals() provides a simpler, stricter equality check based on the === operator. As a result it will not assert two instances of identical objects as they won’t be referentially the same.

  1. Deno.test("Test Assert Strict Equals", () => {
  2. assertStrictEquals(1, 1);
  3. assertStrictEquals("Hello", "Hello");
  4. assertStrictEquals(true, true);
  5. assertStrictEquals(undefined, undefined);
  6. });

The assertStrictEquals() assertion is best used when you wish to make a precise check against two primitive types.

Equality for numbers

When testing equality between numbers, it is important to keep in mind that some of them cannot be accurately depicted by IEEE-754 double-precision floating-point representation.

That’s especially true when working with decimal numbers, where assertStrictEquals() may work in some cases but not in others:

  1. Deno.test("Test Assert Strict Equals with float numbers", () => {
  2. assertStrictEquals(0.25 + 0.25, 0.25);
  3. assertThrows(() => assertStrictEquals(0.1 + 0.2, 0.3));
  4. //0.1 + 0.2 will be stored as 0.30000000000000004 instead of 0.3
  5. });

Instead, assertAlmostEquals() provides a way to test that given numbers are close enough to be considered equals. Default tolerance is set to 1e-7 though it is possible to change it by passing a third optional parameter.

  1. Deno.test("Test Assert Almost Equals", () => {
  2. assertAlmostEquals(0.1 + 0.2, 0.3);
  3. assertAlmostEquals(0.1 + 0.2, 0.3, 1e-16);
  4. assertThrows(() => assertAlmostEquals(0.1 + 0.2, 0.3, 1e-17));
  5. });

Instance types

To check if a object is an instance of a specific constructor, you can use assertInstanceOf(). This has the added benefit that it lets TypeScript know the passed in variable has a specific type:

  1. Deno.test("Test Assert Instance Type", () => {
  2. const variable = new Date() as unknown;
  3. assertInstanceOf(variable, Date);
  4. // This won't cause type errors now now that
  5. // it's type has been asserted against.
  6. variable.getDay();
  7. });

Contains

There are two methods available to assert a value contains a value, assertStringIncludes() and assertArrayIncludes().

The assertStringIncludes() assertion does a simple includes check on a string to see if it contains the expected string.

  1. Deno.test("Test Assert String Contains", () => {
  2. assertStringIncludes("Hello World", "Hello");
  3. });

The assertArrayIncludes() assertion is slightly more advanced and can find both a value within an array and an array of values within an array.

  1. Deno.test("Test Assert Array Contains", () => {
  2. assertArrayIncludes([1, 2, 3], [1]);
  3. assertArrayIncludes([1, 2, 3], [1, 2]);
  4. assertArrayIncludes(Array.from("Hello World"), Array.from("Hello"));
  5. });

Regex

You can assert regular expressions via assertMatch() and assertNotMatch() assertions.

  1. Deno.test("Test Assert Match", () => {
  2. assertMatch("abcdefghi", new RegExp("def"));
  3. const basicUrl = new RegExp("^https?://[a-z.]+.com$");
  4. assertMatch("https://www.google.com", basicUrl);
  5. assertMatch("http://facebook.com", basicUrl);
  6. });
  7. Deno.test("Test Assert Not Match", () => {
  8. assertNotMatch("abcdefghi", new RegExp("jkl"));
  9. const basicUrl = new RegExp("^https?://[a-z.]+.com$");
  10. assertNotMatch("https://deno.land/", basicUrl);
  11. });

Object

Use assertObjectMatch to check that a JavaScript object matches a subset of the properties of an object.

  1. // Simple subset
  2. assertObjectMatch(
  3. { foo: true, bar: false },
  4. {
  5. foo: true,
  6. },
  7. );

Throws

There are two ways to assert whether something throws an error in Deno, assertThrows() and assertRejects(). Both assertions allow you to check an Error has been thrown, the type of error thrown and what the message was.

The difference between the two assertions is assertThrows() accepts a standard function and assertRejects() accepts a function which returns a Promise.

The assertThrows() assertion will check an error has been thrown, and optionally will check the thrown error is of the correct type, and assert the error message is as expected.

  1. Deno.test("Test Assert Throws", () => {
  2. assertThrows(
  3. () => {
  4. throw new Error("Panic!");
  5. },
  6. Error,
  7. "Panic!",
  8. );
  9. });

The assertRejects() assertion is a little more complicated, mainly because it deals with Promises. But basically it will catch thrown errors or rejections in Promises. You can also optionally check for the error type and error message. This can be used similar to assertThrows() but with async functions.

  1. Deno.test("Test Assert Throws Async", () => {
  2. await assertRejects(
  3. () => {
  4. return new Promise(() => {
  5. throw new Error("Panic! Threw Error");
  6. });
  7. },
  8. Error,
  9. "Panic! Threw Error",
  10. );
  11. await assertRejects(
  12. () => {
  13. return Promise.reject(new Error("Panic! Reject Error"));
  14. },
  15. Error,
  16. "Panic! Reject Error",
  17. );
  18. });

Custom Messages

Each of Deno’s built-in assertions allow you to overwrite the standard CLI error message if you wish. For instance this example will output “Values Don’t Match!” rather than the standard CLI error message.

  1. Deno.test("Test Assert Equal Fail Custom Message", () => {
  2. assertEquals(1, 2, "Values Don't Match!");
  3. });

Custom Tests

While Deno comes with powerful assertions modules but there is always something specific to the project you can add. Creating custom assertion function can improve readability and reduce the amount of code.

  1. function assertPowerOf(actual: number, expected: number, msg?: string): void {
  2. let received = actual;
  3. while (received % expected === 0) received = received / expected;
  4. if (received !== 1) {
  5. if (!msg) {
  6. msg = `actual: "${actual}" expected to be a power of : "${expected}"`;
  7. }
  8. throw new AssertionError(msg);
  9. }
  10. }

Use this matcher in your code like this:

  1. Deno.test("Test Assert PowerOf", () => {
  2. assertPowerOf(8, 2);
  3. assertPowerOf(11, 4);
  4. });