Deno 断言
为了帮助开发者编写测试,Deno 标准库提供了内置的 断言模块,可从
https://deno.land/std/testing/asserts.ts 导入。
import { assert } from "https://deno.land/std/testing/asserts.ts";
Deno.test("Hello Test", () => {
assert("Hello");
});
断言模块提供了九个断言函数:
- assert(expr: unknown, msg = ""): asserts expr
- assertEquals(actual: unknown, expected: unknown, msg?: string): void
- assertNotEquals(actual: unknown, expected: unknown, msg?: string): void
- assertStrictEquals(actual: unknown, expected: unknown, msg?: string): void
- assertStringContains(actual: string, expected: string, msg?: string): void
- assertArrayContains(actual: unknown[], expected: unknown[], msg?: string): void
- assertMatch(actual: string, expected: RegExp, msg?: string): void
- assertThrows(fn: () => void, ErrorClass?: Constructor, msgIncludes = "", msg?: string): Error
- assertThrowsAsync(fn: () => Promise<void>, ErrorClass?: Constructor, msgIncludes = "", msg?: string): Promise<Error>
断言
assert 方法是一个简单的“真值”断言,可用于断言任何可以推导为 true 的值。
Deno.test("Test Assert", () => {
assert(1);
assert("Hello");
assert(true);
});
相等性
可用的相等性断言有三个:assertEquals(),assertNotEquals() 和 assertStrictEquals(). assertEquals() 和 assertNotEquals() 方法提供常规的相等性检查,并能够断言基本类型和对象的相等性。
Deno.test("Test Assert Equals", () => {
assertEquals(1, 1);
assertEquals("Hello", "Hello");
assertEquals(true, true);
assertEquals(undefined, undefined);
assertEquals(null, null);
assertEquals(new Date(), new Date());
assertEquals(new RegExp("abc"), new RegExp("abc"));
class Foo {}
const foo1 = new Foo();
const foo2 = new Foo();
assertEquals(foo1, foo2);
});
Deno.test("Test Assert Not Equals", () => {
assertNotEquals(1, 2);
assertNotEquals("Hello", "World");
assertNotEquals(true, false);
assertNotEquals(undefined, "");
assertNotEquals(new Date(), Date.now());
assertNotEquals(new RegExp("abc"), new RegExp("def"));
});
assertStrictEquals() 基于 === 运算符提供了更简单、严格的检查。相同对象的两个实例不会判断为相等,因为引用不相同。
Deno.test("Test Assert Strict Equals", () => {
assertStrictEquals(1, 1);
assertStrictEquals("Hello", "Hello");
assertStrictEquals(true, true);
assertStrictEquals(undefined, undefined);
});
assertStrictEquals() 最好用于精确判断两个基本类型的相等性。
自定义消息
Deno 的每个内置断言都允许您覆盖标准 CLI 错误消息。 这个示例将输出 "Values Don't Match!",而不是标准 CLI 错误消息。
Deno.test("Test Assert Equal Fail Custom Message", () => {
assertEquals(1, 2, "Values Don't Match!");
});