62 lines
2.3 KiB
JavaScript
62 lines
2.3 KiB
JavaScript
'use strict'
|
||
|
||
// src/ui-workbench-hooks.js 的 useOutputsSync 行为测试(P1 跨标签输出索引同步)
|
||
|
||
const assert = require('assert')
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
const vm = require('vm')
|
||
|
||
const root = path.resolve(__dirname, '..')
|
||
const src = fs.readFileSync(path.join(root, 'src', 'ui-workbench-hooks.js'), 'utf8')
|
||
|
||
const listeners = {}
|
||
const bcs = []
|
||
const effects = []
|
||
const fakeReact = {
|
||
useState: (init) => [typeof init === 'function' ? init() : init, () => {}],
|
||
useEffect: (fn) => { effects.push(fn) },
|
||
useRef: (init) => ({ current: init }),
|
||
useMemo: (fn) => fn(),
|
||
}
|
||
const sandbox = {
|
||
React: fakeReact,
|
||
addEventListener: (type, h) => { (listeners[type] = listeners[type] || []).push(h) },
|
||
removeEventListener: (type, h) => { listeners[type] = (listeners[type] || []).filter((x) => x !== h) },
|
||
BroadcastChannel: class {
|
||
constructor(name) { this.name = name; this.onmessage = null; this.closed = false; bcs.push(this) }
|
||
postMessage() {}
|
||
close() { this.closed = true }
|
||
},
|
||
console,
|
||
}
|
||
sandbox.window = sandbox
|
||
vm.runInNewContext(src, sandbox)
|
||
const H = sandbox.IWBWorkbenchHooks
|
||
assert.ok(H && typeof H.useOutputsSync === 'function', 'hooks 应导出 useOutputsSync')
|
||
|
||
let called = 0
|
||
H.useOutputsSync('iwb_web_outputs', 'iwb_outputs_sync', () => { called++ })
|
||
assert.strictEqual(effects.length, 1, 'useOutputsSync 应注册一个 effect')
|
||
const cleanup = effects[0]()
|
||
|
||
const storageHandlers = listeners['storage'] || []
|
||
assert.strictEqual(storageHandlers.length, 1, '应注册 storage 监听')
|
||
assert.ok(bcs.length === 1 && bcs[0].name === 'iwb_outputs_sync', '应创建 BroadcastChannel')
|
||
|
||
storageHandlers[0]({ key: 'iwb_web_outputs' })
|
||
assert.strictEqual(called, 1, 'OUT_KEY 变化应触发 onSync')
|
||
storageHandlers[0]({ key: 'other_key' })
|
||
assert.strictEqual(called, 1, '其它 key 不应触发')
|
||
storageHandlers[0]({ key: null })
|
||
assert.strictEqual(called, 2, 'localStorage.clear()(key=null)应触发')
|
||
|
||
bcs[0].onmessage()
|
||
assert.strictEqual(called, 3, 'BroadcastChannel 消息应作为兜底触发 onSync')
|
||
|
||
cleanup()
|
||
assert.strictEqual((listeners['storage'] || []).length, 0, 'cleanup 应移除 storage 监听')
|
||
assert.strictEqual(bcs[0].closed, true, 'cleanup 应关闭 BroadcastChannel')
|
||
|
||
console.log('ui-workbench-hooks checks passed')
|