| 1 | // EventHandler mock for Jest tests |
| 2 | class MockEventHandler { |
| 3 | constructor(port) { |
| 4 | this._events = { |
| 5 | emit: [], |
| 6 | on: [], |
| 7 | send: [] |
| 8 | }; |
| 9 | this._responses = {}; |
| 10 | this._options = {}; |
| 11 | |
| 12 | // Initialize with a mock port structure |
| 13 | this._port = port || { |
| 14 | onMessage: { |
| 15 | addListener: jest.fn() |
| 16 | }, |
| 17 | onDisconnect: { |
| 18 | addListener: jest.fn() |
| 19 | }, |
| 20 | postMessage: jest.fn(), |
| 21 | disconnect: jest.fn(), |
| 22 | name: 'mock-port' |
| 23 | }; |
| 24 | |
| 25 | this._handlers = new Map(); |
| 26 | this._handlerObject = null; |
| 27 | } |
| 28 | |
| 29 | // Configure the mock with specific responses and options |
| 30 | configure(responses = {}, options = {}) { |
| 31 | this._responses = {...this._responses, ...responses}; |
| 32 | this._options = {...this._options, ...options}; |
| 33 | } |
| 34 | |
| 35 | // Reset the mock state |
| 36 | reset() { |
| 37 | this._events = { |
| 38 | emit: [], |
| 39 | on: [], |
| 40 | send: [] |
| 41 | }; |
| 42 | this._responses = {}; |
| 43 | this._options = {}; |
| 44 | this.on.mockClear(); |
| 45 | this.emit.mockClear(); |
| 46 | this.send.mockClear(); |
| 47 | this.disconnect.mockClear(); |
| 48 | } |
| 49 | |
| 50 | on = jest.fn(event => { |
| 51 | this._events.on.push(event); |
| 52 | }); |
| 53 | emit = jest.fn(event => { |
| 54 | this._events.emit.push(event); |
| 55 | }); |
| 56 | send = jest.fn(event => { |
| 57 | this._events.send.push(event); |
| 58 | |
| 59 | const {shouldFail = false, failingEvents = []} = this._options; |
| 60 | |