You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/TicketUploadRuntimeBehavior...

209 lines
7.9 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
const source = fs.readFileSync(new URL('../public/cloud/ticket-upload.js', import.meta.url), 'utf8');
class FakeClassList {
constructor() { this.values = new Set(); }
add(value) { this.values.add(value); }
remove(value) { this.values.delete(value); }
contains(value) { return this.values.has(value); }
}
class FakeElement {
constructor(tagName = 'div') {
this.tagName = tagName.toUpperCase();
this.children = [];
this.listeners = new Map();
this.classList = new FakeClassList();
this.attributes = new Map();
this.hidden = false;
this.files = [];
this.value = '';
this._innerHTML = '';
}
addEventListener(name, callback) {
const handlers = this.listeners.get(name) || [];
handlers.push(callback);
this.listeners.set(name, handlers);
}
removeEventListener(name, callback) {
this.listeners.set(name, (this.listeners.get(name) || []).filter((item) => item !== callback));
}
dispatch(name, detail = {}) {
const event = { preventDefault() {}, ...detail };
(this.listeners.get(name) || []).forEach((callback) => callback(event));
}
appendChild(child) { this.children.push(child); return child; }
focus() { this.focused = true; }
setAttribute(name, value) { this.attributes.set(name, String(value)); }
get innerHTML() { return this._innerHTML; }
set innerHTML(value) { this._innerHTML = value; this.children = []; }
set textContent(value) { this._textContent = String(value); }
get textContent() { return this._textContent || ''; }
}
class FakeFormData {
constructor() { this.entries = []; }
append(...entry) { this.entries.push(entry); }
}
class FakeDataTransfer {
constructor() {
this.files = [];
this.items = { add: (file) => this.files.push(file) };
}
}
class FakeEventTarget {
constructor() { this.listeners = new Map(); }
addEventListener(name, callback) { this.listeners.set(name, callback); }
trigger(name, event = {}) {
const callback = this.listeners.get(name);
if (callback) callback(event);
}
}
class FakeXMLHttpRequest extends FakeEventTarget {
static instances = [];
constructor() {
super();
this.upload = new FakeEventTarget();
this.headers = {};
this.status = 0;
this.responseText = '';
FakeXMLHttpRequest.instances.push(this);
}
open(method, url) { this.method = method; this.url = url; }
setRequestHeader(name, value) { this.headers[name] = value; }
send(body) { this.body = body; }
abort() { this.trigger('abort'); }
}
const createdUrls = [];
const revokedUrls = [];
const document = { createElement: (tagName) => new FakeElement(tagName) };
const window = {
VenixUserCopy: {
text(key) { return `运行时发布文案:${key}`; },
},
DataTransfer: FakeDataTransfer,
FormData: FakeFormData,
XMLHttpRequest: FakeXMLHttpRequest,
URL: {
createObjectURL(file) { const url = `blob:${file.name}:${createdUrls.length}`; createdUrls.push(url); return url; },
revokeObjectURL(url) { revokedUrls.push(url); },
},
};
vm.runInNewContext(source, { window, document, Promise });
const runtime = window.VenixTicketUpload;
assert.deepEqual(Object.keys(runtime).sort(), ['mount', 'submit', 'validate']);
const input = new FakeElement('input');
const output = new FakeElement('div');
const dropzone = new FakeElement('label');
const root = {
querySelector(selector) {
if (selector.startsWith('input')) return input;
if (selector === '[data-file-list]') return output;
if (selector === '.vu-support-dropzone') return dropzone;
return null;
},
};
const errors = [];
const mounted = runtime.mount(root, { onError: (message) => errors.push(message) });
const first = { name: 'one.png', size: 100, type: 'image/png', lastModified: 1 };
const second = { name: 'two.jpg', size: 200, type: 'image/jpeg', lastModified: 2 };
input.files = [first];
input.dispatch('change');
assert.equal(mounted.files().length, 1);
input.files = [first, second];
input.dispatch('change');
assert.equal(Array.from(mounted.files(), (file) => file.name).join(','), 'one.png,two.jpg', 'new selections append and duplicate files collapse');
assert.ok(revokedUrls.length >= 1, 'rerender revokes stale preview URLs');
dropzone.dispatch('drop', { dataTransfer: { files: [second] } });
assert.equal(mounted.files().length, 2, 'drop selection uses the same dedupe path');
const firstRemove = output.children[0].children.at(-1);
firstRemove.dispatch('click');
assert.equal(Array.from(mounted.files(), (file) => file.name).join(','), 'two.jpg');
assert.equal(output.children[0].children.at(-1).focused, true, 'removing a file restores focus to the remaining remove action');
output.children[0].children.at(-1).dispatch('click');
assert.equal(input.focused, true, 'removing the last file restores focus to the file input');
input.files = [{ name: 'bad.txt', size: 10, type: 'text/plain', lastModified: 3 }];
input.dispatch('change');
assert.equal(mounted.files().length, 0, 'invalid append preserves the accepted selection');
assert.equal(errors.at(-1), '运行时发布文案:tickets.upload.unsupported_type');
mounted.destroy();
assert.equal(revokedUrls.length, createdUrls.length, 'destroy revokes every live preview URL');
let progress = 0;
const success = runtime.submit({
url: '/ticket',
fields: { content: 'hello' },
files: [second],
headers: { 'Idempotency-Key': 'request-1' },
onProgress: (value) => { progress = value; },
});
let xhr = FakeXMLHttpRequest.instances.at(-1);
assert.equal(xhr.timeout, 60000);
assert.equal(xhr.headers['Idempotency-Key'], 'request-1');
assert.deepEqual(xhr.body.entries.map((entry) => entry[0]), ['content', 'attachments[]']);
xhr.upload.trigger('progress', { lengthComputable: true, loaded: 5, total: 10 });
assert.equal(progress, 50);
xhr.status = 200;
xhr.responseText = '{"ret":1,"msg":"ok"}';
xhr.trigger('load');
assert.equal((await success.promise).msg, 'ok');
assert.equal(progress, 100);
const cancelled = runtime.submit({ url: '/ticket', fields: {}, files: [] });
cancelled.abort();
await assert.rejects(cancelled.promise, (error) => error.kind === 'cancelled'
&& error.copyKey === 'tickets.upload.cancelled'
&& error.mutationMayHaveApplied === false);
const timedOut = runtime.submit({ url: '/ticket', fields: {}, files: [], timeout: 25 });
xhr = FakeXMLHttpRequest.instances.at(-1);
assert.equal(xhr.timeout, 25);
xhr.trigger('timeout');
await assert.rejects(timedOut.promise, (error) => error.kind === 'timeout'
&& error.copyKey === 'tickets.upload.timeout'
&& error.mutationMayHaveApplied === true);
const rejected = runtime.submit({ url: '/ticket', fields: {}, files: [] });
xhr = FakeXMLHttpRequest.instances.at(-1);
xhr.status = 422;
xhr.responseText = '{"ret":0,"msg":"不应展示的服务端原始错误"}';
xhr.trigger('load');
await assert.rejects(rejected.promise, (error) =>
error.copyKey === 'tickets.upload.http_error'
&& error.mutationMayHaveApplied === false
&& !error.message.includes('不应展示的服务端原始错误'));
const knownRejection = runtime.submit({ url: '/ticket', fields: {}, files: [] });
xhr = FakeXMLHttpRequest.instances.at(-1);
xhr.status = 200;
xhr.responseText = '{"ret":0,"msg":"同样不能展示的业务错误"}';
xhr.trigger('load');
await assert.rejects(knownRejection.promise, (error) =>
error.copyKey === 'tickets.feedback.rejected'
&& error.mutationMayHaveApplied === false
&& !error.message.includes('同样不能展示的业务错误'));
const uncertainServerFailure = runtime.submit({ url: '/ticket', fields: {}, files: [] });
xhr = FakeXMLHttpRequest.instances.at(-1);
xhr.status = 503;
xhr.responseText = '{"ret":0,"msg":"服务端提交后发生异常"}';
xhr.trigger('load');
await assert.rejects(uncertainServerFailure.promise, (error) =>
error.copyKey === 'tickets.feedback.effect_unknown'
&& error.mutationMayHaveApplied === true
&& !error.message.includes('服务端提交后发生异常'));
console.log('Ticket upload runtime behavior passed.');