Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: assertInstanceOf #5749

Closed
wants to merge 7 commits into from
20 changes: 20 additions & 0 deletions std/testing/asserts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,26 @@ export async function assertThrowsAsync(
return error;
}

/**
* Assert an object is an instance of a particular type. This is useful to check
* polymorphic relationships, for instance check B is an instance of A if B
* extends A.
*/
export function assertInstanceOf(
actual: unknown,
expected: Function,
msg?: string
): void {
if (!(actual instanceof expected)) {
if (!msg) {
msg = `actual: "${format(actual)}" expected to match: "${format(
expected
)}"`;
}
throw new AssertionError(msg);
}
}

/** Use this to stub out methods that will throw when invoked. */
export function unimplemented(msg?: string): never {
throw new AssertionError(msg || "unimplemented");
Expand Down
56 changes: 55 additions & 1 deletion std/testing/asserts_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ import {
assertEquals,
assertStrictEq,
assertThrows,
assertInstanceOf,
AssertionError,
equal,
fail,
unimplemented,
unreachable,
} from "./asserts.ts";
import { red, green, gray, bold, yellow } from "../fmt/colors.ts";
import { red, green, gray, bold, yellow, cyan } from "../fmt/colors.ts";
const { test } = Deno;

test("testingEqual", function (): void {
Expand Down Expand Up @@ -391,3 +392,56 @@ test({
);
},
});

test({
name: "testingAssertInstanceOf",
fn(): void {
class Foo {}
const foo = new Foo();
assertInstanceOf(foo, Foo);

const myString = new String("Hello");
assertInstanceOf(myString, String);

const myArray = new Array(["Hello"]);
assertInstanceOf(myArray, Array);

class Person {}
class Adult extends Person {}

function getThing(): Person {
return new Adult();
}

assertInstanceOf(getThing(), Adult);

class A {}
class B extends A {}

const b = new B();

assertInstanceOf(b, A);
},
});

test({
name: "testingAssertInstanceOf Fail",
fn(): void {
class Foo {}
class Bar {}
const foo = new Foo();
assertThrows(
(): void => assertInstanceOf(foo, Bar),
AssertionError,
`actual: "Foo {}" expected to match: "${cyan("[Function: Bar]")}"`
);

assertThrows(
(): void => assertInstanceOf(new String(), Array),
AssertionError,
`actual: "${cyan(`[String: ""]`)}" expected to match: "${cyan(
"[Function: Array]"
)}"`
);
},
});