std/assert/assert_is_error_test.ts
Michael Herzner b649680328
test(assert): improve test coverage (#4679)
* test(assert): improve test coverage

* chore: format

* chore: lint

* nits

---------

Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
2024-05-07 00:08:16 +00:00

75 lines
2.2 KiB
TypeScript

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { AssertionError, assertIsError, assertThrows } from "./mod.ts";
class CustomError extends Error {}
class AnotherCustomError extends Error {}
Deno.test("assertIsError() throws when given value isn't error", () => {
assertThrows(
() => assertIsError("Panic!", undefined, "Panic!"),
AssertionError,
`Expected "error" to be an Error object.`,
);
assertThrows(
() => assertIsError(null),
AssertionError,
`Expected "error" to be an Error object.`,
);
assertThrows(
() => assertIsError(undefined),
AssertionError,
`Expected "error" to be an Error object.`,
);
});
Deno.test("assertIsError() allows subclass of Error", () => {
assertIsError(new AssertionError("Fail!"), Error, "Fail!");
});
Deno.test("assertIsError() allows custom error", () => {
assertIsError(new CustomError("failed"), CustomError, "fail");
assertThrows(
() => assertIsError(new AnotherCustomError("failed"), CustomError, "fail"),
AssertionError,
'Expected error to be instance of "CustomError", but was "AnotherCustomError".',
);
});
Deno.test("assertIsError() throws with message diff containing double quotes", () => {
assertThrows(
() =>
assertIsError(
new CustomError('error with "double quotes"'),
CustomError,
'doesn\'t include "this message"',
),
AssertionError,
`Expected error message to include "doesn't include \\"this message\\"", but got "error with \\"double quotes\\"".`,
);
});
Deno.test("assertIsError() throws when given value doesn't match regex ", () => {
assertIsError(new AssertionError("Regex test"), Error, /ege/);
assertThrows(
() => assertIsError(new AssertionError("Regex test"), Error, /egg/),
Error,
`Expected error message to include /egg/, but got "Regex test"`,
);
});
Deno.test("assertIsError() throws with custom message", () => {
assertThrows(
() =>
assertIsError(
new CustomError("failed"),
AnotherCustomError,
"fail",
"CUSTOM MESSAGE",
),
AssertionError,
'Expected error to be instance of "AnotherCustomError", but was "CustomError": CUSTOM MESSAGE',
);
});