Files
Clipboard/test/window-lifecycle.test.js
2026-09-12 13:59:12 +08:00

86 lines
2.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const mainSrc = fs.readFileSync(path.join(__dirname, '..', 'main.js'), 'utf8');
const rendererSrc = fs.readFileSync(path.join(__dirname, '..', 'renderer', 'renderer.js'), 'utf8');
let passed = 0;
function check(name, fn) {
try { fn(); console.log(' ok -', name); passed++; }
catch (e) { console.error(' FAIL -', name, e.message); process.exitCode = 1; }
}
const toggleWindow = mainSrc.match(/function toggleWindow\s*\([\s\S]*?\n\}/);
check('toggleWindow 函数存在', () => {
assert.ok(toggleWindow, '找不到 toggleWindow');
});
check('toggleWindow 在 show() 之前调用 positionAtTopCenter', () => {
const fn = toggleWindow[0];
// 两次 show() 调用的索引位置
const showIndices = [];
let from = 0;
while (true) {
const i = fn.indexOf('mainWindow.show()', from);
if (i < 0) break;
showIndices.push(i);
from = i + 1;
}
assert.ok(showIndices.length >= 2, `期望至少 2 处 mainWindow.show(),找到 ${showIndices.length}`);
const posIndices = [];
from = 0;
while (true) {
const i = fn.indexOf('positionAtTopCenter()', from);
if (i < 0) break;
posIndices.push(i);
from = i + 1;
}
assert.strictEqual(posIndices.length, showIndices.length,
`positionAtTopCenter 调用次数(${posIndices.length}) 应与 show 调用次数(${showIndices.length}) 相同`);
for (let k = 0; k < showIndices.length; k++) {
assert.ok(posIndices[k] < showIndices[k],
`${k + 1}positionAtTopCenter 必须在 show 之前 (pos=${posIndices[k]}, show=${showIndices[k]})`);
}
});
// ---------- renderer 端Esc / × 走 hide(),不再销毁窗口 ----------
check('renderer.js 已解构 hide来自 preload', () => {
assert.ok(
/const\s*\{[\s\S]*?\bhide\b[\s\S]*?\}\s*=\s*window\.api/.test(rendererSrc),
'renderer.js 没从 window.api 解构 hide()'
);
});
check('Esc 路径调用 hide(),不再 window.close()', () => {
// 抓出 Escape 分支整个 if 块(包含 body
const escBlock = rendererSrc.match(/if\s*\(\s*e\.key\s*===\s*'Escape'\s*\)\s*\{[\s\S]*?\n\s{2}\}/);
assert.ok(escBlock, '找不到 Escape 分支');
assert.ok(
/\bhide\s*\(/.test(escBlock[0]),
'Escape 分支没调 hide()'
);
assert.ok(
!/window\.close\s*\(/.test(escBlock[0]),
'Escape 分支还在用 window.close()'
);
});
check('× 按钮($closeBtnclick 调用 hide(),不再 window.close()', () => {
const onClick = rendererSrc.match(/\$closeBtn\.addEventListener\(\s*'click'[\s\S]*?\}\s*\)\s*;/);
assert.ok(onClick, '找不到 $closeBtn click 处理');
assert.ok(
/\bhide\s*\(/.test(onClick[0]),
'$closeBtn click 没调 hide()'
);
assert.ok(
!/window\.close\s*\(/.test(onClick[0]),
'$closeBtn click 还在用 window.close()'
);
});
console.log(`\n${passed} checks passed`);