import { expect, test, describe, it } from 'vitest' import Plugin from '../../lib/core/plugin' describe('Plugin', () => { const testContext = {} it('install plugins', () => { const plugin1 = { name: 'p1', use() {}, before() {} } const plugin2 = { name: 'p2', use2() {} } test('install of options.plugins', () => { const pluginInstance = new Plugin({ plugins: [plugin1, plugin2], hooks: ['before'], context: testContext }) expect(pluginInstance.space.p1).toEqual(plugin1) expect(pluginInstance.space.p2).toEqual(plugin2) }) test('install of install()', () => { const pluginInstance = new Plugin({ hooks: ['before'], context: testContext }) pluginInstance.install([plugin1, plugin2]) expect(pluginInstance.space.p1).toEqual(plugin1) expect(pluginInstance.space.p2).toEqual(plugin2) }) }) it('install and use plugin', () => { const pluginInstance = new Plugin({ hooks: ['before', 'after'], context: testContext }) const samplePlugin = { name: 'samplePlugin', use(context) { context.used = true }, before() { console.log('Before hook executed') }, after() { console.log('After hook executed') } } pluginInstance.use(samplePlugin) test('检查 space 调用', () => { expect(pluginInstance.space.samplePlugin).toEqual(samplePlugin) }) test('检查 hooks', () => { expect(pluginInstance.get('before').length).toBe(1) }) }) it('apply hooks', () => { const pluginInstance = new Plugin({ hooks: ['customHook'], context: testContext }) test('apply customHook', () => { const customHandler = (value) => { expect(value).toBe(42) } pluginInstance.use({ customHook: customHandler }) const appliedHandler = pluginInstance.apply('customHook') appliedHandler(42) }) test('apply not register hooks', () => { let result = null const tempHook = pluginInstance.apply('not-register-hooks', (value) => { expect(value).toBe('not') result = value }) tempHook('not') expect(result).toBe('not') }) test('apply not register hooks function', () => { let result = null const tempHook = pluginInstance.apply('not-register-hooks', 'xxx') expect(tempHook).toBe(null) }) }) it('get hooks', () => { const pluginInstance = new Plugin({ hooks: ['getHook'], context: testContext }) const getHookHandler1 = () => console.log('Get Hook Handler 1') const getHookHandler2 = () => console.log('Get Hook Handler 2') pluginInstance.use({ getHook: getHookHandler1 }) pluginInstance.use({ getHook: getHookHandler2 }) test('get has hooks length', () => { const hooks = pluginInstance.get('getHook') expect(hooks.length).toBe(2) }) test('get not has hooks length', () => { const hooks = pluginInstance.get('getNotHook') expect(hooks.length).toEqual([]) }) }) })