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