Function assertThrows

  • Executes a function, expecting it to throw. If it does not, then it throws.

    To assert that an asynchronous function rejects, use assertRejects.

    Parameters

    • fn: (() => unknown)

      The function to execute.

        • (): unknown
        • Returns unknown

    • Optionalmsg: string

      The optional message to display if the assertion fails.

    Returns unknown

    The error that was thrown.

    import { assertThrows } from "@std/assert";

    assertThrows(() => { throw new TypeError("hello world!"); }); // Doesn't throw
    assertThrows(() => console.log("hello world!")); // Throws
  • Executes a function, expecting it to throw. If it does not, then it throws. An error class and a string that should be included in the error message can also be asserted.

    To assert that an asynchronous function rejects, use assertRejects.

    Type Parameters

    • E extends Error = Error

      The error class to assert.

    Parameters

    • fn: (() => unknown)

      The function to execute.

        • (): unknown
        • Returns unknown

    • ErrorClass: (new (...args: any[]) => E)

      The error class to assert.

        • new (...args): E
        • Parameters

          • Rest...args: any[]

          Returns E

    • OptionalmsgIncludes: string

      The string that should be included in the error message.

    • Optionalmsg: string

      The optional message to display if the assertion fails.

    Returns E

    The error that was thrown.

    import { assertThrows } from "@std/assert";

    assertThrows(() => { throw new TypeError("hello world!"); }, TypeError); // Doesn't throw
    assertThrows(() => { throw new TypeError("hello world!"); }, RangeError); // Throws