import { test } from 'node:test'; import assert from 'node:assert/strict'; import { chain, labelsFor, lookup, makeDog, run } from './main.js'; test('原型链是 实例 → Dog.prototype → Animal.prototype → Object.prototype → null', () => { const dog = makeDog(); assert.deepEqual(chain(dog), [ 'Dog.prototype', 'Animal.prototype', 'Object.prototype', 'null', ]); }); test('实例自有属性 name 在实例上', () => { const dog = makeDog(); const r = lookup(dog, 'name', labelsFor(dog)); assert.equal(r.found, true); assert.equal(r.owner, 'dog 实例'); assert.deepEqual(r.path, []); }); test('speak 被子类原型覆盖,查找在 Dog.prototype 停止', () => { const dog = makeDog(); const r = lookup(dog, 'speak', labelsFor(dog)); assert.equal(r.owner, 'Dog.prototype'); assert.equal(r.value.call(dog), 'Rex barks'); }); test('toString 落在 Object.prototype,路径经过前三层', () => { const dog = makeDog(); const r = lookup(dog, 'toString', labelsFor(dog)); assert.equal(r.owner, 'Object.prototype'); assert.deepEqual(r.path, ['dog 实例', 'Dog.prototype', 'Animal.prototype']); }); test('不存在的属性一路走到 null,返回 undefined', () => { const dog = makeDog(); const r = lookup(dog, 'fly', labelsFor(dog)); assert.equal(r.found, false); assert.equal(r.owner, null); assert.equal(r.value, undefined); assert.equal(r.path.length, 4); }); test('in 会查原型链,Object.hasOwn 不会', () => { const dog = makeDog(); assert.equal('speak' in dog, true); assert.equal(Object.hasOwn(dog, 'speak'), false); assert.equal(Object.hasOwn(dog, 'name'), true); }); test('修正 constructor 后指向正确的构造函数', () => { const dog = makeDog(); assert.equal(dog.constructor.name, 'Dog'); }); test('实例上新增同名属性会遮蔽原型方法', () => { const dog = makeDog(); dog.speak = () => 'own speak'; assert.equal(dog.speak(), 'own speak'); assert.equal(Object.hasOwn(dog, 'speak'), true); }); test('run 输出 8 行场景与两条说明', () => { const out = []; const rows = run((s) => out.push(s)); assert.equal(rows.length, 8); assert.equal(out.length, 11); assert.equal(out[4], 'toString 的归属 => Object.prototype'); });