Skip to main content

@std/assert@1.0.19
Built and signed on GitHub Actions

Works with
This package works with Cloudflare Workers, Node.js, Deno, Bun, Browsers
This package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
This package works with Bun
This package works with Browsers
JSR Score100%
License
MIT
Downloads92,645/wk
Published3 months ago (1.0.19)

Common assertion functions, especially useful for testing

function assertThrows
assertThrows(
fn: () => unknown,
msg?: string
): unknown

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

To assert that an asynchronous function rejects, use assertRejects.

Examples

Usage

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

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

Parameters

fn: () => unknown

The function to execute.

optional
msg: string

The optional message to display if the assertion fails.

Return Type

unknown

The error that was thrown.

assertThrows<E extends Error = Error>(
fn: () => unknown,
ErrorClass: new (...args: any[]) => E,
msgIncludes?: string,
msg?: string
): E

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.

Examples

Usage

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

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

Type Parameters

E extends Error = Error

The error class to assert.

Parameters

fn: () => unknown

The function to execute.

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

The error class to assert.

optional
msgIncludes: string

The string that should be included in the error message.

optional
msg: string

The optional message to display if the assertion fails.

Return Type

The error that was thrown.

Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@std/assert

Import symbol

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

Import directly with a jsr specifier

import { assertThrows } from "jsr:@std/assert/throws";