Files
dpl/scripts/theme-fuc/app.test.mjs
T

302 lines
19 KiB
JavaScript

// Run the theme's real event handlers against a static DOM and delayed API doubles.
// This checks races and business payloads; it is not browser/provider acceptance.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import {JSDOM,VirtualConsole} from '../../codex/output/fuc-theme/test-tools/node_modules/jsdom/lib/api.js';
const jsErrors=[],consoleCapture=new VirtualConsole();consoleCapture.on('jsdomError',error=>jsErrors.push(error));
const dom=new JSDOM('<html><head><style>.modal.fade .modal-dialog{transition:transform .3s ease-out}.modal-backdrop.fade{transition:opacity .15s linear}</style></head><body><div id="app"></div></body></html>',{url:'http://xb.loc/#/login',runScripts:'outside-only',pretendToBeVisual:true,virtualConsole:consoleCapture});
for(const key of ['window','document','DOMParser','localStorage','sessionStorage','location','history','FormData'])globalThis[key]=dom.window[key];
globalThis.innerWidth=1280;
let changeSystemColor;
globalThis.matchMedia=()=>({matches:false,addEventListener(_,listener){changeSystemColor=listener;}});
globalThis.requestAnimationFrame=window.requestAnimationFrame.bind(window);globalThis.cancelAnimationFrame=window.cancelAnimationFrame.bind(window);
window.scrollTo=()=>{};window.ApexCharts=class{render(){return Promise.resolve()}destroy(){}};
const plans=[{id:1,name:'Paid',month_price:1200,transfer_enable:100},{id:2,name:'Free',month_price:0,transfer_enable:10}];
const calls=[],templateRequests=[];
let failWalletTemplate=true, failNoticePage=0, subscriptionExpired=false;
let delayedLogin,delayedCoupon,checkoutAmount=0,checkoutStatus=0,failOrderCheck=false,orders=[];
const payload=(data,status=200)=>({ok:status<400,status,json:async()=>({data})});
globalThis.fetch=async(url,options={})=>{
if(String(url).startsWith('file:')){
const name=new URL(url).pathname.split('/').at(-1);
if(name.endsWith('.html'))templateRequests.push(name);
if(name==='wallet.html'&&failWalletTemplate)return {ok:false,status:503};
return {ok:true,text:()=>fs.readFile(new URL(url),'utf8'),json:async()=>JSON.parse(await fs.readFile(new URL(url),'utf8'))};
}
const path=String(url).replace('/api/v1/','');calls.push({path,body:options.body?JSON.parse(options.body):null});
if(path==='guest/comm/config')return payload({is_captcha:0});
if(path==='passport/auth/login')return new Promise(resolve=>delayedLogin=()=>resolve(payload({auth_data:'Bearer synthetic'})));
if(path==='user/info')return payload({email:'[email protected]',plan_id:2,expired_at:subscriptionExpired?1:null,transfer_enable:1000});
if(path==='user/getSubscribe')return payload({plan_id:2,plan:plans[1],transfer_enable:1000,u:0,d:0,subscribe_url:'http://xb.loc/s/synthetic'});
if(path==='user/comm/config')return payload({withdraw_methods:[]});
if(path.startsWith('user/notice/fetch?current=')){
const current=Number(new URLSearchParams(path.split('?')[1]).get('current'));
if(current===failNoticePage)return payload(null,503);
const offset=(current-1)*5;
const notices=Array.from({length:18},(_,i)=>({id:i+1,title:'归档公告 '+(i+1),content:'归档正文 '+(i+1),created_at:1793836800}));
return {ok:true,status:200,json:async()=>({data:notices.slice(offset,offset+5),total:notices.length})};
}
if(path==='user/plan/fetch')return payload(subscriptionExpired?[{...plans[1],reset_price:400}]:[plans[0]]);
if(path==='user/plan/fetch?id=2')return payload({...plans[1],show:false,sell:false,renew:true,capacity_limit:'Sold out'});
if(path==='user/coupon/check')return new Promise(resolve=>delayedCoupon=()=>resolve(payload({name:'QA'})));
if(path==='user/order/save')return payload('synthetic-order');
if(path==='user/order/fetch')return payload(orders);
if(path==='user/order/detail?trade_no=synthetic-order')return payload({trade_no:'synthetic-order',plan:plans[1],period:'month_price',status:checkoutStatus,total_amount:checkoutAmount});
if(path==='user/order/check?trade_no=synthetic-order')return payload(checkoutStatus,failOrderCheck?503:200);
if(path==='user/order/getPaymentMethod')return payload([{id:17,name:'空中支付 · 微信支付',payment:'Epay'},{id:21,name:'空中支付 · 支付宝',payment:'Epay'}]);
if(path==='user/order/checkout')return payload({type:1,data:'https://pay.example.test/synthetic-only'});
if(path==='user/order/cancel'){
const order=orders.find(order=>order.trade_no===JSON.parse(options.body).trade_no);
if(!order||Number(order.status)!==0)return payload(null,422);
order.status=2;
return payload(true);
}
return payload([]);
};
const append=document.head.append.bind(document.head);
document.head.append=node=>{append(node);if(node.tagName==='SCRIPT')queueMicrotask(()=>{try{window.eval(requireFile(node.src));node.onload?.();}catch(error){node.onerror?.(error);}});if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());};
const insertBefore=document.head.insertBefore.bind(document.head);
document.head.insertBefore=(node,before)=>{const result=insertBefore(node,before);if(node.tagName==='LINK')queueMicrotask(()=>node.onload?.());return result;};
const {readFileSync}=await import('node:fs');const requireFile=url=>readFileSync(new URL(url),'utf8');
const until=async predicate=>{for(let n=0;n<200;n++){if(predicate())return;await new Promise(resolve=>setTimeout(resolve,10));}throw Error('DOM state did not settle');};
const go=async route=>{location.hash='/'+route;await until(()=>document.body.dataset.nativePage===route);};
await import('../../theme/Fuc/assets/app.mjs');
test('login uses original pending text and waits for success confirmation before routing',async()=>{
await until(()=>document.querySelector('[data-form=login]'));assert.deepEqual(templateRequests,['login.html']);const form=document.querySelector('[data-form=login]'),button=form.querySelector('[type=submit]');
form.querySelector('[name=email]').value='[email protected]';form.querySelector('[name=password]').value='synthetic-password';
form.dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
assert.equal(button.textContent,'正在登录');assert.equal(button.disabled,true);await until(()=>delayedLogin);delayedLogin();
await until(()=>document.querySelector('.swal2-confirm'));assert.equal(location.hash,'#/login');
document.querySelector('.swal2-confirm').click();await until(()=>document.body.dataset.nativePage==='dashboard');
assert.equal(calls.find(c=>c.path==='passport/auth/login').body.password,'synthetic-password');
});
test('a delayed coupon response cannot reopen a purchase modal on a different page',async()=>{
await go('plans');document.querySelector('[data-action=buy]').click();await until(()=>document.querySelector('#coupon_modal.show'));
const form=document.querySelector('[data-form=purchase-coupon]');form.querySelector('[name=coupon_code]').value='QA';
form.dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));await until(()=>delayedCoupon);
await go('profile');delayedCoupon();await new Promise(resolve=>setTimeout(resolve,50));
assert.equal(document.querySelector('#order_modal.show'),null);assert.equal(document.body.dataset.nativePage,'profile');
assert.equal(calls.filter(c=>c.path==='user/order/save').length,0);
});
test('canceling the source-style subscription reset never calls the reset API',async()=>{
document.querySelector('[data-target="#sublink-modal"]').click();await until(()=>document.querySelector('#sublink-modal.show'));
document.querySelector('[data-action=reset-security]').click();await until(()=>document.querySelector('.swal2-cancel'));
document.querySelector('.swal2-cancel').click();await new Promise(resolve=>setTimeout(resolve,20));
assert.equal(calls.some(c=>c.path==='user/resetSecurity'),false);
});
test('leaving during the original modal transition leaves no late component errors',async()=>{
await go('plans');document.querySelector('[data-action=buy]').click();
await go('profile');await new Promise(resolve=>setTimeout(resolve,700));
assert.deepEqual(jsErrors.map(e=>e.message),[]);
});
test('manual renewal of an off-sale owned plan keeps the actual XB plan and period',async()=>{
await go('plans');
const renewal=document.querySelector('[data-action=buy][data-id="2"][data-period="month_price"]');assert.ok(renewal);
renewal.click();await until(()=>document.querySelector('#coupon_modal.show'));
document.querySelector('#coupon_modal [data-form=purchase-coupon]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
await until(()=>document.querySelector('#order_modal.show'));
document.querySelector('#order_modal [data-form=purchase]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
await until(()=>document.body.dataset.nativePage==='checkout');
assert.deepEqual(calls.filter(c=>c.path==='user/order/save').at(-1).body,{plan_id:2,period:'month_price'});
const modal=document.querySelector('#fuc-checkout-modal');
assert.ok(document.querySelector('[data-action=buy][data-id="2"]'));
assert.ok(modal.querySelector('[data-form=checkout]'));
await until(()=>modal.classList.contains('show'));
modal.querySelector('[aria-label="关闭订单详情"]').click();
await until(()=>document.body.dataset.nativePage==='plans');
assert.equal(location.hash,'#/plans');
location.hash='/checkout/synthetic-order';
await until(()=>document.body.dataset.nativePage==='checkout');
assert.equal(document.querySelector('#fuc-checkout-modal'),null);
assert.ok(document.querySelector('[data-form=checkout]'));
});
test('the old plan URL opens the order list, with an unpaid order accessible on its page',async()=>{
orders=Array.from({length:20},(_,i)=>({trade_no:'paid-'+i,status:3}));
orders.push({trade_no:'synthetic-order',status:0});
try{
location.hash='/myplan';
await until(()=>document.body.dataset.nativePage==='orders');
assert.equal(location.hash,'#/orders');
const menu=document.querySelector('.navigation-main a[href="#/orders"]');
assert.equal(menu.querySelector('.menu-title').textContent,'套餐订单');
assert.ok(menu.querySelector('.icon-hard-drive'));
assert.equal(menu.closest('li').nextElementSibling.querySelector('a').getAttribute('href'),'#/wallet');
assert.equal(document.querySelector('[data-pending-order]'),null);
assert.doesNotMatch(document.querySelector('tbody').textContent,/synthetic-order/);
document.querySelector('[data-action=next]').click();
const unpaidLink=()=>document.querySelector('tbody a[href="#/checkout/synthetic-order?from=orders&page=2"]');
await until(unpaidLink);
assert.equal(unpaidLink().textContent,'继续支付');
unpaidLink().click();
await until(()=>document.querySelector('#fuc-checkout-modal.show'));
assert.equal(location.hash,'#/checkout/synthetic-order?from=orders&page=2');
assert.match(document.querySelector('.fuc-pagination').textContent,/第 2 \/ 2 页/);
assert.ok(unpaidLink());
document.querySelector('#fuc-checkout-modal [data-action=native-dismiss]').click();
await until(()=>document.body.dataset.nativePage==='orders');
assert.equal(location.hash,'#/orders?page=2');
assert.ok(unpaidLink());
orders.pop();
location.hash='/subscribe';
await until(()=>location.hash==='#/orders'&&document.querySelector('tbody tr'));
}finally{orders=[];}
});
test('pending orders can be canceled from their rows after confirmation',async()=>{
await go('plans');
orders=[{trade_no:'first-order',status:0},{trade_no:'row-order',status:'0'},{trade_no:'paid-order',status:3}];
try{
await go('orders');
const sent=()=>calls.filter(call=>call.path==='user/order/cancel').map(call=>call.body.trade_no);
const row=()=>document.querySelector('tbody button[data-trade-no="row-order"]');
const first=()=>document.querySelector('tbody button[data-trade-no="first-order"]');
assert.equal(document.querySelector('[data-pending-order]'),null);
assert.equal(document.querySelector('tbody button[data-trade-no="paid-order"]'),null);
assert.equal(document.querySelector('tbody a[href="#/checkout/paid-order?from=orders"]').textContent,'查看');
row().click();
assert.equal(row().textContent,'再次点击确认取消');
assert.deepEqual(sent(),[]);
row().click();
await until(()=>!row());
first().click();
assert.deepEqual(sent(),['row-order']);
first().click();
await until(()=>!first());
assert.deepEqual(sent(),['row-order','first-order']);
assert.equal(location.hash,'#/orders');
assert.equal(document.querySelectorAll('tbody button[data-trade-no]').length,0);
}finally{orders=[];}
});
test('a shop order opens checkout over the shop and closes back to it',async()=>{
await go('plans');
document.querySelector('[data-action=buy]').click();
await until(()=>document.querySelector('#coupon_modal.show'));
document.querySelector('[data-form=purchase-coupon]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
await until(()=>document.querySelector('#order_modal.show'));
document.querySelector('#order_modal [data-form=purchase]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
await until(()=>document.querySelector('#fuc-checkout-modal.show'));
assert.equal(location.hash,'#/checkout/synthetic-order?from=plans');
assert.ok(document.querySelector('[data-action=buy]'));
document.querySelector('#fuc-checkout-modal [data-action=native-dismiss]').click();
await until(()=>document.body.dataset.nativePage==='plans');
assert.equal(location.hash,'#/plans');
});
test('payment cards show short labels and open the selected native cashier directly',async t=>{
const opened=[];
t.mock.method(window.HTMLAnchorElement.prototype,'click',function(){opened.push([this.href,this.target]);});
checkoutAmount=1200;location.hash='/checkout/synthetic-order?from=plans';
await until(()=>document.querySelector('#fuc-checkout-modal input[name=method]'));
const form=document.querySelector('#fuc-checkout-modal [data-form=checkout]');
const first=form.querySelector('input[value="17"]'),second=form.querySelector('input[value="21"]');
assert.deepEqual([...form.querySelectorAll('.nav-text')].map(node=>node.textContent),['微信','支付宝']);
assert.equal(first.checked,true);assert.equal(document.querySelector('#fuc-checkout-modal details'),null);
second.click();
assert.equal(second.checked,true);assert.equal(first.nextElementSibling.classList.contains('active'),false);
assert.equal(second.nextElementSibling.classList.contains('active'),true);
form.dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
await until(()=>calls.some(c=>c.path==='user/order/checkout'));
assert.deepEqual(calls.find(c=>c.path==='user/order/checkout').body,{trade_no:'synthetic-order',method:'21'});
await until(()=>opened.length>0);
assert.deepEqual(opened,[['https://pay.example.test/synthetic-only','_self']]);
assert.equal(document.querySelector('#payment-result').textContent,'');
checkoutAmount=0;await go('plans');
});
test('payment refresh is a fallback for failed or slow checks and clears when the order advances',async t=>{
t.mock.method(window.HTMLAnchorElement.prototype,'click',()=>{});
const realSetTimeout=globalThis.setTimeout;
const start=Date.now();
let now=start,nextCheck;
t.mock.method(Date,'now',()=>now);
t.mock.method(globalThis,'setTimeout',(callback,delay,...args)=>{
if(delay!==5000)return realSetTimeout(callback,delay,...args);
const timer=realSetTimeout(callback,delay,...args);
nextCheck=async()=>{clearTimeout(timer);await callback(...args);};
return timer;
});
const refresh=()=>document.querySelector('[data-action=refresh-payment]');
const check=async()=>{assert.ok(nextCheck);const run=nextCheck;nextCheck=null;await run();};
checkoutAmount=1200;
try{
location.hash='/checkout/synthetic-order?from=orders';
await until(()=>refresh());
assert.equal(refresh().hidden,true);
document.querySelector('[data-form=checkout]').dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
await until(()=>nextCheck);
now=start+5000;await check();
assert.equal(refresh().hidden,true);
failOrderCheck=true;await check();
assert.equal(refresh().hidden,false);
failOrderCheck=false;now=start+60000;await check();
assert.equal(refresh().hidden,false);
checkoutStatus=1;await check();
assert.match(document.querySelector('#fuc-checkout-modal .fuc-checkout-product').textContent,/开通中/);
assert.equal(refresh().hidden,true);
checkoutStatus=3;await check();
assert.match(document.querySelector('#fuc-checkout-modal .fuc-checkout-product').textContent,/已完成/);
assert.equal(refresh(),null);
}finally{
checkoutAmount=0;checkoutStatus=0;failOrderCheck=false;await go('plans');
}
});
test('the announcement page shows all four native XB pages in order',async()=>{
calls.length=0;
await go('notices');
assert.deepEqual(calls.filter(c=>c.path.startsWith('user/notice/fetch?current=')).map(c=>c.path.split('=')[1]),['1','2','3','4']);
const headings=[...document.querySelectorAll('h5')].map(node=>node.textContent.trim()).filter(title=>title.startsWith('归档公告 '));
assert.deepEqual(headings,Array.from({length:18},(_,i)=>'归档公告 '+(i+1)));
});
test('a failed wallet template stays isolated and can be retried',async()=>{
location.hash='/wallet';
await until(()=>document.querySelector('#app [data-action=retry]'));
assert.match(document.querySelector('#app [role=alert]').textContent,/模板加载失败/);
failWalletTemplate=false;
document.querySelector('#app [data-action=retry]').click();
await until(()=>document.querySelector('[data-form=gift]'));
assert.equal(templateRequests.filter(name=>name==='wallet.html').length,2);
});
test('the dashboard preserves account details and loaded notices after a notice-page failure',async()=>{
try {
for(const failedPage of [1,2]){
await go('profile');
failNoticePage=failedPage;
await go('dashboard');
const dashboard=document.querySelector('#dashboard-analytics');
assert.ok(dashboard);
assert.match(dashboard.textContent,/公告暂时无法加载/);
assert.equal(dashboard.textContent.includes('归档正文 1'),failedPage===2);
assert.equal(document.querySelector('#app [data-action=retry]'),null);
}
}finally{failNoticePage=0;}
});
test('system color changes preserve the checkout modal and scroll lock',async()=>{
localStorage.setItem('fuc_themeMod','system');
try {
location.hash='/checkout/synthetic-order?from=orders';
await until(()=>document.querySelector('#fuc-checkout-modal.show'));
const modal=document.querySelector('#fuc-checkout-modal');
for(const matches of [true,false]){
changeSystemColor({matches});
assert.equal(document.body.classList.contains('dark-layout'),matches);
assert.ok(document.body.classList.contains('modal-open'));
assert.equal(document.querySelector('#fuc-checkout-modal.show'),modal);
assert.equal(document.querySelectorAll('.modal-backdrop').length,1);
}
modal.querySelector('[data-action=native-dismiss]').click();
await until(()=>document.body.dataset.nativePage==='orders');
assert.equal(document.body.classList.contains('modal-open'),false);
}finally{localStorage.removeItem('fuc_themeMod');}
});
test('an expired owner can buy a regular period but cannot enter traffic reset',async()=>{
subscriptionExpired=true;
try {
await go('plans');
assert.ok(document.querySelector('[data-action=buy][data-period=month_price]:enabled'));
assert.equal(document.querySelector('[data-period=reset_price]'),null);
location.hash='/purchase/2?period=reset_price';
await until(()=>document.querySelector('#app [role=alert]'));
assert.match(document.querySelector('#app [role=alert]').textContent,/此套餐或计费周期不可购买/);
assert.equal(document.querySelector('[data-form=purchase]'),null);
}finally{subscriptionExpired=false;}
});
test.after(()=>{window.Pace.stop();dom.window.close();});