addons/isl/src/TestingMessageBus.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import type {MessageBus, MessageBusStatus} from './MessageBus';
b69ab319import type {Disposable} from './types';
b69ab3110
b69ab3111/** This fake implementation of MessageBus expects you to manually simulate messages from the server */
b69ab3112export class TestingEventBus implements MessageBus {
b69ab3113 public handlers: Array<(e: MessageEvent<string>) => void> = [];
b69ab3114 public sent: Array<string> = [];
b69ab3115 onMessage(handler: (event: MessageEvent<string>) => void | Promise<void>): Disposable {
b69ab3116 this.handlers.push(handler);
b69ab3117 return {dispose: () => {}};
b69ab3118 }
b69ab3119
b69ab3120 postMessage(message: string) {
b69ab3121 this.sent.push(message);
b69ab3122 }
b69ab3123
b69ab3124 public statusChangeHandlers = new Set<(status: MessageBusStatus) => unknown>();
b69ab3125 onChangeStatus(handler: (status: MessageBusStatus) => unknown): Disposable {
b69ab3126 // pretend connection opens immediately
b69ab3127 handler({type: 'open'});
b69ab3128 this.statusChangeHandlers.add(handler);
b69ab3129
b69ab3130 return {
b69ab3131 dispose: () => {
b69ab3132 this.statusChangeHandlers.delete(handler);
b69ab3133 },
b69ab3134 };
b69ab3135 }
b69ab3136
b69ab3137 // additional methods for testing
b69ab3138
b69ab3139 simulateMessage(message: string) {
b69ab3140 this.handlers.forEach(handle => handle({data: message} as MessageEvent<string>));
b69ab3141 }
b69ab3142
b69ab3143 resetTestMessages() {
b69ab3144 this.sent = [];
b69ab3145 // Emulate reconnect to trigger serverAPI.onSetup callbacks.
b69ab3146 this.simulateServerStatusChange({type: 'reconnecting'});
b69ab3147 this.simulateServerStatusChange({type: 'open'});
b69ab3148 }
b69ab3149
b69ab3150 simulateServerStatusChange(newStatus: MessageBusStatus) {
b69ab3151 for (const handler of this.statusChangeHandlers) {
b69ab3152 handler(newStatus);
b69ab3153 }
b69ab3154 }
b69ab3155}