assert在软件开发中,*断言*声明了关于值或代码段必须为真的事实。如果它们不是真的,则会抛出异常。Node.js 通过其内置模块 assert 支持断言 - 例如
import * as assert from 'assert/strict';
assert.equal(3 + 5, 8);此断言声明 3 加 5 的预期结果为 8。导入语句使用 推荐的 strict 版本 的 assert。
在本书中,断言以两种方式使用:记录代码示例中的结果和实现测试驱动的练习。
在代码示例中,断言表示预期结果。以以下函数为例
function id(x) {
return x;
}id() 返回其参数。我们可以通过断言来展示它的作用
assert.equal(id('abc'), 'abc');在示例中,我通常省略导入 assert 的语句。
使用断言的动机是
本书的练习是测试驱动的,通过测试框架 Mocha 进行。测试中的检查是通过 assert 的方法进行的。
以下是此类测试的示例
// For the exercise, you must implement the function hello().
// The test checks if you have done it properly.
test('First exercise', () => {
assert.equal(hello('world'), 'Hello world!');
assert.equal(hello('Jane'), 'Hello Jane!');
assert.equal(hello('John'), 'Hello John!');
assert.equal(hello(''), 'Hello !');
});有关更多信息,请参阅 §10 “测验和练习入门”。
严格的 equal() 使用 === 来比较值。因此,一个对象只等于它自己 - 即使另一个对象具有相同的内容(因为 === 不比较对象的内容,只比较它们的标识)
assert.notEqual({foo: 1}, {foo: 1});deepEqual() 是比较对象的更好选择
assert.deepEqual({foo: 1}, {foo: 1});此方法也适用于数组
assert.notEqual(['a', 'b', 'c'], ['a', 'b', 'c']);
assert.deepEqual(['a', 'b', 'c'], ['a', 'b', 'c']);assert有关完整文档,请参阅 Node.js 文档。
function equal(actual: any, expected: any, message?: string): void
actual === expected 必须为 true。如果不是,则抛出 AssertionError。
assert.equal(3+3, 6);function notEqual(actual: any, expected: any, message?: string): void
actual !== expected 必须为 true。如果不是,则抛出 AssertionError。
assert.notEqual(3+3, 22);可选的最后一个参数 message 可用于解释断言的内容。如果断言失败,则使用该消息设置抛出的 AssertionError。
let e;
try {
const x = 3;
assert.equal(x, 8, 'x must be equal to 8')
} catch (err) {
assert.equal(
String(err),
'AssertionError [ERR_ASSERTION]: x must be equal to 8');
}function deepEqual(actual: any, expected: any, message?: string): void
actual 必须与 expected 深度相等。如果不是,则抛出 AssertionError。
assert.deepEqual([1,2,3], [1,2,3]);
assert.deepEqual([], []);
// To .equal(), an object is only equal to itself:
assert.notEqual([], []);function notDeepEqual(actual: any, expected: any, message?: string): void
actual 不能与 expected 深度相等。如果是,则抛出 AssertionError。
assert.notDeepEqual([1,2,3], [1,2]);如果您想(或预期)接收异常,则需要 throws():此函数调用其第一个参数,即函数 block,并且仅在其抛出异常时才成功。可以使用其他参数来指定该异常必须是什么样的。
function throws(block: Function, message?: string): void
assert.throws(
() => {
null.prop;
}
);function throws(block: Function, error: Function, message?: string): void
assert.throws(
() => {
null.prop;
},
TypeError
);function throws(block: Function, error: RegExp, message?: string): void
assert.throws(
() => {
null.prop;
},
/^TypeError: Cannot read properties of null \(reading 'prop'\)$/
);function throws(block: Function, error: Object, message?: string): void
assert.throws(
() => {
null.prop;
},
{
name: 'TypeError',
message: "Cannot read properties of null (reading 'prop')",
}
);function fail(message: string | Error): never
在调用时始终抛出 AssertionError。这在单元测试中偶尔有用。
try {
functionThatShouldThrow();
assert.fail();
} catch (_) {
// Success
} 测验
请参阅 测验应用。