rabbit-harmony/tests/unimp-host-runtime.test.cjs

50 lines
2.2 KiB
JavaScript

const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const { test } = require('node:test');
const ts = require(process.env.UNIMP_TYPESCRIPT || 'C:/Program Files/Huawei/DevEco Studio/tools/hvigor/hvigor/node_modules/typescript');
function fixture(failInit = false) {
const watchers = new Map([['hostWatcher', () => {}]]);
const calls = [], exports = {};
const filename = path.join(__dirname, '../common/src/main/ets/utils/UniMpHostRuntime.ets');
const code = ts.transpileModule(fs.readFileSync(filename, 'utf8'), {
fileName: 'UniMpHostRuntime.ts',
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 }
}).outputText;
const mocks = {
'@dcloudio/uni-app-runtime': { init: (ability, stage, config) => {
calls.push({ ability, stage, config });
// SDK 5.14 registers this synchronously; historical crashes arrive later.
watchers.set('uniAppCrashWatcher', () => { throw new TypeError('Cannot read property appId of null'); });
if (failInit) throw new Error('SDK init failed');
} },
'@kit.PerformanceAnalysisKit': { hiAppEvent: { removeWatcher: watcher => watchers.delete(watcher.name) } }
};
vm.runInNewContext(code, { exports, require: name => {
assert.ok(mocks[name], name);
return mocks[name];
} });
return { init: exports.initUniMpRuntime, watchers, calls };
}
test('cold start and recreated stages cannot replay old crashes into mini-program storage', () => {
const f = fixture(), ability = {}, stage = {};
for (let i = 0; i < 3; i++) {
f.init(ability, stage, true);
assert.doesNotThrow(() => f.watchers.forEach(callback => callback()));
assert.equal(f.watchers.has('uniAppCrashWatcher'), false);
assert.equal(f.watchers.has('hostWatcher'), true);
}
assert.equal(f.calls[0].ability, ability);
assert.equal(f.calls[0].stage, stage);
assert.equal(f.calls[0].config.debug, true);
});
test('partial SDK initialization removes the unsafe watcher and preserves the original error', () => {
const f = fixture(true);
assert.throws(() => f.init({}, {}, false), /SDK init failed/);
assert.equal(f.watchers.has('uniAppCrashWatcher'), false);
});