示例工程 19-dom-events

19-dom-events/01-event-flow/main.test.mjs

javascript · 1.0 KB

运行:19 · 事件流三阶段

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { run, simulateDispatch } from './main.js';
 
test('捕获从外到内,冒泡从内到外', () => {
  assert.deepEqual(simulateDispatch(['outer', 'inner', 'button']), [
    'capture:outer',
    'capture:inner',
    'target:button',
    'bubble:inner',
    'bubble:outer',
  ]);
});
 
test('单节点只有目标阶段', () => {
  assert.deepEqual(simulateDispatch(['button']), ['target:button']);
});
 
test('空路径返回空数组', () => {
  assert.deepEqual(simulateDispatch([]), []);
  assert.deepEqual(simulateDispatch(null), []);
});
 
test('深层嵌套的捕获/冒泡对称', () => {
  const order = simulateDispatch(['a', 'b', 'c', 'd']);
  assert.deepEqual(order.slice(0, 3), ['capture:a', 'capture:b', 'capture:c']);
  assert.deepEqual(order.slice(4), ['bubble:c', 'bubble:b', 'bubble:a']);
});
 
test('run 输出三阶段顺序', () => {
  const out = [];
  run((s) => out.push(s));
  assert.match(out[0], /capture:outer → capture:inner → target:button/);
});