feat(framework): core EventBus(类型化+故障隔离)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventBus } from '../../YouleNexus/assets/framework/core/events.ts';
|
||||
|
||||
test('on/emit 传递参数', () => {
|
||||
const bus = new EventBus<{ hi: [number, string] }>();
|
||||
let got: [number, string] | null = null;
|
||||
bus.on('hi', (n, s) => { got = [n, s]; });
|
||||
bus.emit('hi', 7, 'x');
|
||||
assert.deepEqual(got, [7, 'x']);
|
||||
});
|
||||
|
||||
test('off 取消订阅', () => {
|
||||
const bus = new EventBus<{ ping: [] }>();
|
||||
let count = 0;
|
||||
const fn = () => { count++; };
|
||||
bus.on('ping', fn);
|
||||
bus.emit('ping');
|
||||
bus.off('ping', fn);
|
||||
bus.emit('ping');
|
||||
assert.equal(count, 1);
|
||||
});
|
||||
|
||||
test('once 只触发一次', () => {
|
||||
const bus = new EventBus<{ ping: [] }>();
|
||||
let count = 0;
|
||||
bus.once('ping', () => { count++; });
|
||||
bus.emit('ping');
|
||||
bus.emit('ping');
|
||||
assert.equal(count, 1);
|
||||
});
|
||||
|
||||
test('一个事件订阅者抛错不影响其它订阅者', () => {
|
||||
const bus = new EventBus<{ ping: [] }>();
|
||||
let reached = false;
|
||||
bus.on('ping', () => { throw new Error('boom'); });
|
||||
bus.on('ping', () => { reached = true; });
|
||||
bus.emit('ping');
|
||||
assert.equal(reached, true);
|
||||
});
|
||||
Reference in New Issue
Block a user