Skip to main content
Home
This release is 18 versions behind 1.0.16 — the latest version of @std/assert. Jump to latest

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

Common assertion functions, especially useful for testing

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 Score
100%
Published
2 years ago (0.225.3)
Package root>assert_is_error.ts
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. // This module is browser compatible. import { AssertionError } from "./assertion_error.ts"; import { stripAnsiCode } from "jsr:/@std/internal@^1.0.0/styles"; /** * Make an assertion that `error` is an `Error`. * If not then an error will be thrown. * An error class and a string that should be included in the * error message can also be asserted. * * @example * ```ts * import { assertIsError } from "@std/assert/assert-is-error"; * * assertIsError(null); // Throws * assertIsError(new RangeError("Out of range")); // Doesn't throw * assertIsError(new RangeError("Out of range"), SyntaxError); // Throws * assertIsError(new RangeError("Out of range"), SyntaxError, "Out of range"); // Doesn't throw * assertIsError(new RangeError("Out of range"), SyntaxError, "Within range"); // Throws * ``` */ export function assertIsError<E extends Error = Error>( error: unknown, // deno-lint-ignore no-explicit-any ErrorClass?: new (...args: any[]) => E, msgMatches?: string | RegExp, msg?: string, ): asserts error is E { const msgSuffix = msg ? `: ${msg}` : "."; if (!(error instanceof Error)) { throw new AssertionError( `Expected "error" to be an Error object${msgSuffix}}`, ); } if (ErrorClass && !(error instanceof ErrorClass)) { msg = `Expected error to be instance of "${ErrorClass.name}", but was "${error?.constructor?.name}"${msgSuffix}`; throw new AssertionError(msg); } let msgCheck; if (typeof msgMatches === "string") { msgCheck = stripAnsiCode(error.message).includes( stripAnsiCode(msgMatches), ); } if (msgMatches instanceof RegExp) { msgCheck = msgMatches.test(stripAnsiCode(error.message)); } if (msgMatches && !msgCheck) { msg = `Expected error message to include ${ msgMatches instanceof RegExp ? msgMatches.toString() : JSON.stringify(msgMatches) }, but got ${JSON.stringify(error?.message)}${msgSuffix}`; throw new AssertionError(msg); } }