assert.strictEqual(actual, expected[, message])
actual<any>expected<any>message<string> | <Error> | <Function> 后缀printf类似的参数,以防它被用作格式字符串。如果消息是一个函数,当比较失败时将调用它。该函数接收actual和expected参数,并必须返回一个将作为错误消息使用的字符串。printf类似的格式字符串和函数在通过参数传递时对性能有益。此外,它还可以轻松实现漂亮的格式化。
根据 Object.is() 判断,测试 actual 和 expected 参数是否严格相等。
🌐 Tests strict equality between the actual and expected parameters as
determined by Object.is().
import assert from 'node:assert/strict';
assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
// ^
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
assert.strictEqual(apples, oranges, 'apples %s !== oranges %s', apples, oranges);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identical
assert.strictEqual(apples, oranges, (actual, expected) => {
// Do 'heavy' computations
return `I expected ${expected} but I got ${actual}`;
});
// AssertionError [ERR_ASSERTION]: I expected oranges but I got applesconst assert = require('node:assert/strict');
assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
// ^
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
assert.strictEqual(apples, oranges, 'apples %s !== oranges %s', apples, oranges);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identical
assert.strictEqual(apples, oranges, (actual, expected) => {
// Do 'heavy' computations
return `I expected ${expected} but I got ${actual}`;
});
// AssertionError [ERR_ASSERTION]: I expected oranges but I got apples如果值不完全相等,将抛出一个 AssertionError,并且其 message 属性设置为 message 参数的值。如果 message 参数未定义,将分配一个默认的错误消息。如果 message 参数是 <Error> 的实例,则将抛出它本身,而不是 AssertionError。
🌐 If the values are not strictly equal, an AssertionError is thrown with a
message property set equal to the value of the message parameter. If the
message parameter is undefined, a default error message is assigned. If the
message parameter is an instance of <Error> then it will be thrown
instead of the AssertionError.