示例工程 19-dom-events
19-dom-events/04-intersection-observer/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { run, selectVisible, summarize } from './main.js';
const entries = [
{ isIntersecting: true, intersectionRatio: 1, target: { id: 'a' } },
{ isIntersecting: true, intersectionRatio: 0.2, target: { id: 'b' } },
{ isIntersecting: false, intersectionRatio: 0, target: { id: 'c' } },
{ isIntersecting: true, intersectionRatio: 0.05, target: { id: 'd' } },
];
test('只选可见且达到阈值的元素', () => {
assert.deepEqual(selectVisible(entries, 0.1), ['a', 'b']);
});
test('阈值可以调整', () => {
assert.deepEqual(selectVisible(entries, 0.05), ['a', 'b', 'd']);
assert.deepEqual(selectVisible(entries, 0.5), ['a']);
});
test('summary 统计可见与未触发数量', () => {
assert.deepEqual(summarize(entries, 0.1), { total: 4, visible: ['a', 'b'], hidden: 2 });
});
test('空列表返回零值', () => {
assert.deepEqual(summarize([]), { total: 0, visible: [], hidden: 0 });
});
test('run 输出可见列表与结论', () => {
const out = [];
const result = run((s) => out.push(s));
assert.deepEqual(result.visible, ['a', 'b']);
assert.match(out[0], /a, b/);
});