mirror of
https://github.com/KingHWJ/WeReadBoard.git
synced 2026-11-03 18:24:58 +08:00
46 lines
1.2 KiB
JavaScript
46 lines
1.2 KiB
JavaScript
const { test } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const vm = require('node:vm');
|
|
|
|
function loadWeApi(fetch) {
|
|
const context = vm.createContext({
|
|
URL,
|
|
fetch,
|
|
location: { origin: 'https://example.test' },
|
|
});
|
|
context.window = context;
|
|
vm.runInContext(fs.readFileSync('static/js/weapi.js', 'utf8'), context);
|
|
return context.WeApi;
|
|
}
|
|
|
|
function jsonResponse(status, payload) {
|
|
return {
|
|
ok: status >= 200 && status < 300,
|
|
status,
|
|
async json() {
|
|
return payload;
|
|
},
|
|
};
|
|
}
|
|
|
|
test('当前接口未部署完成时自动重试兼容接口', async () => {
|
|
const calls = [];
|
|
const legacyBase = '/api/' + 'v' + '2';
|
|
const api = loadWeApi(async url => {
|
|
calls.push(new URL(url).pathname);
|
|
if (new URL(url).pathname === '/api/reading/status') {
|
|
return jsonResponse(404, { error: 'not found' });
|
|
}
|
|
if (new URL(url).pathname === legacyBase + '/status') {
|
|
return jsonResponse(200, { ok: true });
|
|
}
|
|
return jsonResponse(500, { error: 'unexpected path' });
|
|
});
|
|
|
|
const result = await api.status();
|
|
|
|
assert.equal(result.ok, true);
|
|
assert.deepEqual(calls, ['/api/reading/status', legacyBase + '/status']);
|
|
});
|