示例工程 20-network-storage-fetch
20-network-storage-fetch/06-json-losses/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { inspect, run } from './main.js';
const circular = {};
circular.self = circular;
test('对象里的 undefined 被丢弃', () => {
const r = inspect({ a: undefined, b: 1 });
assert.equal(r.text, '{"b":1}');
});
test('数组里的 undefined/函数/Symbol 变成 null', () => {
const r = inspect([undefined, () => {}, Symbol('s')]);
assert.equal(r.text, '[null,null,null]');
});
test('Date 变成 ISO 字符串', () => {
const r = inspect(new Date('2026-01-01T00:00:00.000Z'));
assert.equal(r.text, '"2026-01-01T00:00:00.000Z"');
assert.equal(typeof r.revived, 'string');
});
test('NaN 与 Infinity 变成 null', () => {
assert.equal(inspect({ nan: NaN, inf: Infinity }).text, '{"nan":null,"inf":null}');
});
test('-0 序列化成 0', () => {
assert.equal(inspect({ zero: -0 }).text, '{"zero":0}');
assert.equal(Object.is(JSON.parse('{"zero":0}').zero, 0), true);
});
test('Map 与 Set 变成空对象', () => {
const r = inspect({ map: new Map([['k', 1]]), set: new Set([1]) });
assert.equal(r.text, '{"map":{},"set":{}}');
});
test('BigInt 抛 TypeError', () => {
const r = inspect({ big: 1n });
assert.equal(r.ok, false);
assert.equal(r.error, 'TypeError');
});
test('循环引用抛 TypeError', () => {
const r = inspect(circular);
assert.equal(r.ok, false);
assert.equal(r.error, 'TypeError');
});
test('toJSON 自定义输出', () => {
assert.equal(inspect({ toJSON: () => ({ x: 1 }) }).text, '{"x":1}');
});
test('run 输出九行案例与结论', () => {
const out = [];
const rows = run((s) => out.push(s));
assert.equal(rows.length, 9);
assert.match(out.at(-1), /只支持/);
});