import { describe, expect, test } from 'vitest' import EmitterCore from '../lib/core/emit/core' // 使用 vitest 的 describe 方法定义测试套件 describe('EmitterCore', () => { const emitter = new EmitterCore().getInstance() test('验证 $on $emit 订阅/发布 参数有效性', () => { const handler = (params, expands, type) => { expect(params).toBe(1) expect(expands.test).toBe(1) expect(type).toBe('test') } emitter.$on('test', handler) emitter.$emit('test', 1, { test: 1 }) }) test('验证 $on 多次订阅及 $off 取消订阅', () => { let count = 0 const handler = (val) => { count += val } emitter.$on('test-on', handler) emitter.$on('test-on', handler) emitter.$emit('test-on', 1) // 1 * 2 = 2 expect(count).toBe(2) // 2 + 2 * 2 = 6 emitter.$emit('test-on', 2) expect(count).toBe(6) emitter.$off('test-on') emitter.$emit('test-on', 2) expect(count).toBe(6) }) test('验证 $once 单次订阅', () => { let count = 0 const handler = () => { count++ expect(count).toBe(1) } emitter.$once('test-once', handler) emitter.$emit('test-once') emitter.$emit('test-once') }) describe('验证 plugins 插件 hooks 冒泡', () => { const triggerHooks = [] const testContent = 'test-plugin-hooks' const emitter = new EmitterCore().getInstance() test('use', () => { emitter.use({ use(context) { triggerHooks.push('use') expect(emitter).toMatchObject(context) }, emit(type, event, expands) { triggerHooks.push('emit') if (type === '*') { expect(expands.originEventName).toBe(testContent) } else { expect(type).toBe(testContent) } expect(event).toBe(testContent) expect(expands.name).toBe(testContent) }, once(type) { triggerHooks.push('once') expect(type).toBe(testContent) }, on(type) { triggerHooks.push('on') expect(type).toBe(testContent) }, off(type) { triggerHooks.push('off') expect(type).toBe(testContent) } }) expect(triggerHooks).toEqual(['use']) }) // 应该触发两次 emit [*, test-plugin] test('$emit 应该触发两次 emit [*, test-plugin]', () => { emitter.$emit(testContent, testContent, { name: testContent }) expect(triggerHooks).toEqual(['use', 'emit', 'emit']) }) test('$once 应该触发 [once, on]', () => { // 应该触发 on [once, on] emitter.$once(testContent) expect(triggerHooks).toEqual(['use', 'emit', 'emit', 'once', 'on']) }) test('$off', () => { emitter.$off(testContent) expect(triggerHooks).toEqual(['use', 'emit', 'emit', 'once', 'on', 'off']) }) test('$on', () => { emitter.$on(testContent) expect(triggerHooks).toEqual([ 'use', 'emit', 'emit', 'once', 'on', 'off', 'on' ]) }) }) })