32 lines
2.4 KiB
JavaScript
32 lines
2.4 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import {createApi, soldOut, safeUrl, bytes, money} from '../../theme/Fuc/assets/core.mjs';
|
|
const response = (body,status=200) => ({ok:status<400,status,json:async()=>body});
|
|
test('uses auth_data verbatim, sends writes as JSON, unwraps Resource data',async()=>{
|
|
let call; const api=createApi({getToken:()=> 'Bearer synthetic',fetcher:async(...args)=>{call=args;return response({status:'success',data:{id:7}});}});
|
|
assert.deepEqual(await api('user/update',{remind_expire:1}),{id:7});
|
|
assert.equal(call[0],'/api/v1/user/update'); assert.equal(call[1].headers.Authorization,'Bearer synthetic'); assert.equal(call[1].method,'POST'); assert.equal(call[1].body,'{"remind_expire":1}');
|
|
});
|
|
test('preserves checkout type with data instead of losing payment routing',async()=>{
|
|
const api=createApi({fetcher:async()=>response({type:1,data:'https://payment.example.test/'})});
|
|
assert.deepEqual(await api('user/order/checkout',{}),{type:1,data:'https://payment.example.test/'});
|
|
});
|
|
test('401 clears auth and rejects; business failure in HTTP200 also rejects',async()=>{
|
|
let expired=false; const api=createApi({onUnauthorized:()=>{expired=true;},fetcher:async()=>response({message:'expired'},401)});
|
|
await assert.rejects(api('user/info'),/expired/); assert.equal(expired,true);
|
|
await assert.rejects(createApi({fetcher:async()=>response({status:'fail',message:'sold out'})})('user/order/save',{}),/sold out/);
|
|
});
|
|
test('does not treat non-JSON HTML as successful API data',async()=>{
|
|
await assert.rejects(createApi({fetcher:async()=>({ok:true,status:200,json:async()=>{throw Error('html');}})})('user/info'),/有效数据/);
|
|
});
|
|
test('stock null and positive are available, zero and localized sold-out are not',()=>{
|
|
for(const capacity_limit of [null,10,'8']) assert.equal(soldOut({capacity_limit}),false);
|
|
for(const capacity_limit of [0,'0','Sold out','已售罄']) assert.equal(soldOut({capacity_limit}),true);
|
|
assert.equal(soldOut({capacity_limit:100,capacity_remaining:0}),true);
|
|
});
|
|
test('rejects script URLs and embedded credentials; formats actual XB money and bytes',()=>{
|
|
assert.equal(safeUrl('javascript:alert(1)'), ''); assert.equal(safeUrl('https://user:[email protected]'), '');
|
|
assert.equal(safeUrl('https://example.test/sub'), 'https://example.test/sub');
|
|
assert.equal(money(1200),'¥12.00'); assert.equal(bytes(1024**3),'1.00 GB'); assert.equal(bytes(1024**2),'1.00 MB'); assert.equal(bytes(-1),'0 B');
|
|
});
|