Files
youle_cocos/cocoscreator_projects/framework-tests/helpers/fake-transport.ts
T

60 lines
2.0 KiB
TypeScript

import type { Transport } from '../../YouleNexus/assets/framework/net/transport.ts';
/** 内存 Transport:模拟服务器。用 microtask 队列异步触发回调,贴近真实 WS 时序。 */
export class FakeTransport implements Transport {
sent: string[] = [];
url = '';
connectCalls = 0;
closeCalls = 0;
private openCb?: () => void;
private msgCb?: (f: string) => void;
private closeCb?: () => void;
private pending: Array<() => void> = [];
private closed = false;
private connectFailure: unknown = null;
connect(url: string): void {
this.connectCalls++;
this.url = url;
if (this.connectFailure !== null) {
const error = this.connectFailure;
this.connectFailure = null;
throw error;
}
this.pending.push(() => this.openCb?.());
}
send(frame: string): void { if (!this.closed) this.sent.push(frame); }
close(): void {
this.closeCalls++;
if (this.closed) return;
this.closed = true;
this.pending.push(() => this.closeCb?.());
}
onOpen(cb: () => void): void { this.openCb = cb; }
onMessage(cb: (f: string) => void): void { this.msgCb = cb; }
onClose(cb: () => void): void { this.closeCb = cb; }
/** 测试侧:令下一次 connect 同步失败。 */
failNextConnect(error: unknown): void { this.connectFailure = error; }
/** 测试侧:模拟服务器推一帧给客户端。 */
serverPush(frame: string): void { this.pending.push(() => this.msgCb?.(frame)); }
/** 测试侧:模拟远端 close;允许重复信号以验证连接代际去重。 */
serverClose(): void {
this.closed = true;
this.pending.push(() => this.closeCb?.());
}
/** 测试侧:生产 adapter 的 error 最终收敛到 close 生命周期。 */
serverError(): void {
this.closed = true;
this.pending.push(() => this.closeCb?.());
}
/** 冲刷所有挂起回调(解析微任务)。 */
async flush(): Promise<void> {
while (this.pending.length) { const fn = this.pending.shift()!; fn(); await Promise.resolve(); }
}
}