实现说明
node:assert 提供 deepStrictEqual——内建表面,不涉及任何包。
各个操作都建立在顶层绑定之上:restored、expected。
使用要点
- 唯一的导入
node:assert属于 Node.js 标准库。 - 直接运行文件,输出会带上标签,比如
restored matches expected:、key order ignored:、array order differences rejected——输出的每一行都能指回产生它的那次调用。
常见问题
有第三方依赖吗?
不需要。导入解析到 Node.js 核心模块,运行时自带。
核心语句
const restored = JSON.parse('{"id":7,"tags":["cache","slow"],"meta":{"tries":2}}');
const expected = { id: 7, tags: ['cache', 'slow'], meta: { tries: 2 } };
deepStrictEqual({ a: 1, b: 2 }, { b: 2, a: 1 });
代码示例
import { deepStrictEqual } from 'node:assert';
// deepStrictEqual compares structure, not identity, and checks prototypes
const restored = JSON.parse('{"id":7,"tags":["cache","slow"],"meta":{"tries":2}}');
const expected = { id: 7, tags: ['cache', 'slow'], meta: { tries: 2 } };
deepStrictEqual(restored, expected);
console.log('restored matches expected:', true);
// object key order does not matter
deepStrictEqual({ a: 1, b: 2 }, { b: 2, a: 1 });
console.log('key order ignored:', true);
// array order does matter
try {
deepStrictEqual([1, 2], [2, 1]);
} catch {
console.log('array order differences rejected');
}