Files
perler-beads-webui/tests/client.test.ts
T

9 lines
1.4 KiB
TypeScript

import {test} from 'node:test'
import {strict as assert} from 'node:assert'
import {api} from '../src/api.ts'
test('client uses centralized same-origin API, Bearer token, JSON body and invalidates expired sessions',async()=>{
let stored:string|null='test-session',events:string[]=[];Object.defineProperty(globalThis,'sessionStorage',{value:{getItem:()=>stored,removeItem:()=>{stored=null}},configurable:true});Object.defineProperty(globalThis,'window',{value:{dispatchEvent:(event:Event)=>events.push(event.type)},configurable:true});let previous=globalThis.fetch;let calls:{url:string;init:RequestInit}[]=[];
globalThis.fetch=async(url,init)=>{calls.push({url:String(url),init:init!});return new Response(JSON.stringify({code:200,msg:'ok',data:{status:'accepted'}}),{headers:{'Content-Type':'application/json'}})};
try {assert.deepEqual(await api('/service-requests/task','PATCH',{status:'accepted'}),{status:'accepted'});assert.equal(calls[0]!.url,'/api/service-requests/task');assert.equal((calls[0]!.init.headers as Record<string,string>).Authorization,'Bearer test-session');assert.equal(calls[0]!.init.body,'{"status":"accepted"}');globalThis.fetch=async()=>new Response(JSON.stringify({code:403,msg:'会话过期',data:null}));await assert.rejects(api('/me'),/会话过期/);assert.equal(stored,null);assert.deepEqual(events,['auth-expired'])}finally{globalThis.fetch=previous}
})