|
| 1 | +import { describe, it, expect, beforeEach, vi } from 'vitest' |
| 2 | +import { MarketWS } from '../src/adapters/ws/MarketWS' |
| 3 | + |
| 4 | +class FakeWS { |
| 5 | + constructor(url) { |
| 6 | + this.url = url |
| 7 | + FakeWS.instances.push(this) |
| 8 | + // open immediately (sync) for deterministic test |
| 9 | + this.onopen && this.onopen() |
| 10 | + } |
| 11 | + send(data) { this.lastSent = data } |
| 12 | + close() { this.closed = true } |
| 13 | + // test helper |
| 14 | + emit(msg) { this.onmessage && this.onmessage({ data: JSON.stringify(msg) }) } |
| 15 | +} |
| 16 | +FakeWS.instances = [] |
| 17 | + |
| 18 | +describe('MarketWS adapter', () => { |
| 19 | + beforeEach(() => { |
| 20 | + FakeWS.instances = [] |
| 21 | + global.WebSocket = FakeWS |
| 22 | + }) |
| 23 | + |
| 24 | + it('subscribes and forwards tick messages for the pair', async () => { |
| 25 | + const adapter = new MarketWS({ url: 'ws://test.local/ws' }) |
| 26 | + let received = [] |
| 27 | + const unsubscribe = adapter.subscribe('BTCUSDT', (tick) => received.push(tick)) |
| 28 | + |
| 29 | + // simulate server tick |
| 30 | + const ws = FakeWS.instances[0] |
| 31 | + ws.emit({ type: 'tick', pair: 'BTCUSDT', bid: '1', ask: '2' }) |
| 32 | + |
| 33 | + // assertions |
| 34 | + expect(ws.url).toBe('ws://test.local/ws') |
| 35 | + expect(ws.lastSent).toBe(JSON.stringify({ type: 'sub', pair: 'BTCUSDT' })) |
| 36 | + expect(received.length).toBe(1) |
| 37 | + expect(received[0]).toEqual({ bid: '1', ask: '2', pair: 'BTCUSDT' }) |
| 38 | + |
| 39 | + // unsubscribe should close |
| 40 | + unsubscribe() |
| 41 | + expect(ws.closed).toBe(true) |
| 42 | + }) |
| 43 | +}) |
0 commit comments