示例工程 19-dom-events
19-dom-events/02-delegation/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { countListeners, findDelegatedTarget, run } from './main.js';
const nodes = {
button: { id: 'button', parent: 'li' },
li: { id: 'li', parent: 'ul' },
ul: { id: 'ul', parent: null },
};
const api = {
matches: (node, selector) => selector === 'button[data-id]' && node.id === 'button',
parentOf: (node) => (node.parent ? nodes[node.parent] : null),
};
test('从目标向上找到匹配的按钮', () => {
assert.equal(findDelegatedTarget(nodes.button, 'button[data-id]', api).id, 'button');
});
test('从子元素向上找到祖先按钮', () => {
const span = { id: 'span', parent: 'button' };
const local = { ...nodes, span };
const found = findDelegatedTarget(span, 'button[data-id]', {
...api,
parentOf: (node) => (node.parent ? local[node.parent] : null),
});
assert.equal(found.id, 'button');
});
test('没有匹配时返回 null', () => {
assert.equal(
findDelegatedTarget(nodes.button, 'a', { matches: () => false, parentOf: api.parentOf }),
null,
);
});
test('监听器数量:直接绑定 N 个,委托 1 个', () => {
assert.equal(countListeners(1000, 'direct'), 1000);
assert.equal(countListeners(1000, 'delegated'), 1);
});
test('run 输出查找与监听器数量', () => {
const out = [];
const result = run((s) => out.push(s));
assert.equal(result.found, 'button');
assert.match(out[1], /直接绑定 1000 个监听器,委托 1 个/);
});