| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import type {MessageBus, MessageBusStatus} from './MessageBus'; |
| b69ab31 | | | 9 | import type {Disposable} from './types'; |
| b69ab31 | | | 10 | |
| b69ab31 | | | 11 | /** This fake implementation of MessageBus expects you to manually simulate messages from the server */ |
| b69ab31 | | | 12 | export class TestingEventBus implements MessageBus { |
| b69ab31 | | | 13 | public handlers: Array<(e: MessageEvent<string>) => void> = []; |
| b69ab31 | | | 14 | public sent: Array<string> = []; |
| b69ab31 | | | 15 | onMessage(handler: (event: MessageEvent<string>) => void | Promise<void>): Disposable { |
| b69ab31 | | | 16 | this.handlers.push(handler); |
| b69ab31 | | | 17 | return {dispose: () => {}}; |
| b69ab31 | | | 18 | } |
| b69ab31 | | | 19 | |
| b69ab31 | | | 20 | postMessage(message: string) { |
| b69ab31 | | | 21 | this.sent.push(message); |
| b69ab31 | | | 22 | } |
| b69ab31 | | | 23 | |
| b69ab31 | | | 24 | public statusChangeHandlers = new Set<(status: MessageBusStatus) => unknown>(); |
| b69ab31 | | | 25 | onChangeStatus(handler: (status: MessageBusStatus) => unknown): Disposable { |
| b69ab31 | | | 26 | // pretend connection opens immediately |
| b69ab31 | | | 27 | handler({type: 'open'}); |
| b69ab31 | | | 28 | this.statusChangeHandlers.add(handler); |
| b69ab31 | | | 29 | |
| b69ab31 | | | 30 | return { |
| b69ab31 | | | 31 | dispose: () => { |
| b69ab31 | | | 32 | this.statusChangeHandlers.delete(handler); |
| b69ab31 | | | 33 | }, |
| b69ab31 | | | 34 | }; |
| b69ab31 | | | 35 | } |
| b69ab31 | | | 36 | |
| b69ab31 | | | 37 | // additional methods for testing |
| b69ab31 | | | 38 | |
| b69ab31 | | | 39 | simulateMessage(message: string) { |
| b69ab31 | | | 40 | this.handlers.forEach(handle => handle({data: message} as MessageEvent<string>)); |
| b69ab31 | | | 41 | } |
| b69ab31 | | | 42 | |
| b69ab31 | | | 43 | resetTestMessages() { |
| b69ab31 | | | 44 | this.sent = []; |
| b69ab31 | | | 45 | // Emulate reconnect to trigger serverAPI.onSetup callbacks. |
| b69ab31 | | | 46 | this.simulateServerStatusChange({type: 'reconnecting'}); |
| b69ab31 | | | 47 | this.simulateServerStatusChange({type: 'open'}); |
| b69ab31 | | | 48 | } |
| b69ab31 | | | 49 | |
| b69ab31 | | | 50 | simulateServerStatusChange(newStatus: MessageBusStatus) { |
| b69ab31 | | | 51 | for (const handler of this.statusChangeHandlers) { |
| b69ab31 | | | 52 | handler(newStatus); |
| b69ab31 | | | 53 | } |
| b69ab31 | | | 54 | } |
| b69ab31 | | | 55 | } |