aboutsummaryrefslogtreecommitdiffstats
path: root/packages/preload/src/contextBridge/__tests__/SophieRendererImpl.spec.ts
blob: 070ebae552ecb095da2624d77c462fc8f6279c9e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
 * Copyright (C)  2021-2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { jest } from '@jest/globals';
import { mocked } from 'jest-mock';
import log from 'loglevel';
import type { IJsonPatch } from 'mobx-state-tree';
import {
  Action,
  MainToRendererIpcMessage,
  RendererToMainIpcMessage,
  SharedStoreSnapshotIn,
  SophieRenderer,
} from '@sophie/shared';

jest.unstable_mockModule('electron', () => ({
  ipcRenderer: {
    invoke: jest.fn(),
    on: jest.fn(),
    send: jest.fn(),
  },
}));

const { ipcRenderer } = await import('electron');

const { createSophieRenderer } = await import('../SophieRendererImpl.js');

const event: Electron.IpcRendererEvent = null as unknown as Electron.IpcRendererEvent;

const snapshot: SharedStoreSnapshotIn = {
  shouldUseDarkColors: true,
};

const invalidSnapshot = {
  shouldUseDarkColors: -1,
} as unknown as SharedStoreSnapshotIn;

const patch: IJsonPatch = {
  op: 'replace',
  path: 'foo',
  value: 'bar',
};

const action: Action = {
  action: 'set-theme-source',
  themeSource: 'dark',
};

const invalidAction = {
  action: 'not-a-valid-action',
} as unknown as Action;

beforeAll(() => {
  log.disableAll();
});

describe('createSophieRenderer', () => {
  it('registers a shared store patch listener', () => {
    createSophieRenderer(false);
    expect(ipcRenderer.on).toHaveBeenCalledWith(
      MainToRendererIpcMessage.SharedStorePatch,
      expect.anything(),
    );
  });
});

describe('SophieRendererImpl', () => {
  let sut: SophieRenderer;
  let onSharedStorePatch: (event: Electron.IpcRendererEvent, patch: unknown) => void;
  let listener = {
    onSnapshot: jest.fn((_snapshot: SharedStoreSnapshotIn) => {}),
    onPatch: jest.fn((_patch: IJsonPatch) => {}),
  };

  beforeEach(() => {
    sut = createSophieRenderer(false);
    onSharedStorePatch = mocked(ipcRenderer.on).mock.calls.find(([channel]) => {
      return channel === MainToRendererIpcMessage.SharedStorePatch;
    })?.[1]!;
  });

  describe('onSharedStoreChange', () => {
    it('should request a snapshot from the main process', async () => {
      mocked(ipcRenderer.invoke).mockResolvedValueOnce(snapshot);
      await sut.onSharedStoreChange(listener);
      expect(ipcRenderer.invoke).toBeCalledWith(RendererToMainIpcMessage.GetSharedStoreSnapshot);
      expect(listener.onSnapshot).toBeCalledWith(snapshot);
    });

    it('should catch IPC errors without exposing them', async () => {
      mocked(ipcRenderer.invoke).mockRejectedValue(new Error('s3cr3t'));
      await expect(sut.onSharedStoreChange(listener)).rejects.not.toHaveProperty(
        'message',
        expect.stringMatching(/s3cr3t/),
      );
      expect(listener.onSnapshot).not.toBeCalled();
    });

    it('should not pass on invalid snapshots', async () => {
      mocked(ipcRenderer.invoke).mockResolvedValueOnce(invalidSnapshot);
      await expect(sut.onSharedStoreChange(listener)).rejects.toBeInstanceOf(Error);
      expect(listener.onSnapshot).not.toBeCalled();
    });
  });

  describe('dispatchAction', () => {
    it('should dispatch valid actions', () => {
      sut.dispatchAction(action);
      expect(ipcRenderer.send).toBeCalledWith(RendererToMainIpcMessage.DispatchAction, action);
    });

    it('should not dispatch invalid actions', () => {
      expect(() => sut.dispatchAction(invalidAction)).toThrowError();
      expect(ipcRenderer.send).not.toBeCalled();
    });
  });

  describe('when no listener is registered', () => {
    it('should discard the received patch without any error', () => {
      onSharedStorePatch(event, patch);
    });
  });

  function itRefusesToRegisterAnotherListener() {
    it('should refuse to register another listener', async () => {
      await expect(sut.onSharedStoreChange(listener)).rejects.toBeInstanceOf(Error);
    });
  }

  function itDoesNotPassPatchesToTheListener(
    name: string = 'should not pass patches to the listener',
  ) {
    it(name, () => {
      onSharedStorePatch(event, patch);
      expect(listener.onPatch).not.toBeCalled();
    });
  }

  describe('when a listener registered successfully', () => {
    beforeEach(async () => {
      mocked(ipcRenderer.invoke).mockResolvedValueOnce(snapshot);
      await sut.onSharedStoreChange(listener);
    });

    it('should pass patches to the listener', () => {
      onSharedStorePatch(event, patch);
      expect(listener.onPatch).toBeCalledWith(patch);
    });

    it('should catch listener errors', () => {
      mocked(listener.onPatch).mockImplementation(() => { throw new Error(); });
      onSharedStorePatch(event, patch);
    });

    itRefusesToRegisterAnotherListener();

    describe('after the listener threw in onPatch', () => {
      beforeEach(() => {
        mocked(listener.onPatch).mockImplementation(() => { throw new Error(); });
        onSharedStorePatch(event, patch);
        listener.onPatch.mockRestore();
      });

      itDoesNotPassPatchesToTheListener('should not pass on patches any more');
    });
  });

  describe('when a listener failed to register due to IPC error', () => {
    beforeEach(async () => {
      mocked(ipcRenderer.invoke).mockRejectedValue(new Error());
      try {
        await sut.onSharedStoreChange(listener);
      } catch {
        // Ignore error.
      }
    });

    itRefusesToRegisterAnotherListener();

    itDoesNotPassPatchesToTheListener();
  });

  describe('when a listener failed to register due to an invalid snapshot', () => {
    beforeEach(async () => {
      mocked(ipcRenderer.invoke).mockResolvedValueOnce(invalidSnapshot);
      try {
        await sut.onSharedStoreChange(listener);
      } catch {
        // Ignore error.
      }
    });

    itRefusesToRegisterAnotherListener();

    itDoesNotPassPatchesToTheListener();
  });

  describe('when a listener failed to register due to listener error', () => {
    beforeEach(async () => {
      mocked(ipcRenderer.invoke).mockResolvedValueOnce(snapshot);
      mocked(listener.onSnapshot).mockImplementation(() => { throw new Error(); });
      try {
        await sut.onSharedStoreChange(listener);
      } catch {
        // Ignore error.
      }
    });

    itRefusesToRegisterAnotherListener();

    itDoesNotPassPatchesToTheListener();
  });

  describe('when it is allowed to replace listeners', () => {
    const snapshot2 = {
      shouldUseDarkColors: false,
    }
    const listener2 = {
      onSnapshot: jest.fn((_snapshot: SharedStoreSnapshotIn) => { }),
      onPatch: jest.fn((_patch: IJsonPatch) => { }),
    };

    it('should fetch a second snapshot', async () => {
      mocked(ipcRenderer.invoke).mockResolvedValueOnce(snapshot2);
      await sut.onSharedStoreChange(listener2);
      expect(ipcRenderer.invoke).toBeCalledWith(RendererToMainIpcMessage.GetSharedStoreSnapshot);
      expect(listener2.onSnapshot).toBeCalledWith(snapshot2);
    });

    it('should pass the second snapshot to the new listener', async () => {
      mocked(ipcRenderer.invoke).mockResolvedValueOnce(snapshot2);
      await sut.onSharedStoreChange(listener2);
      onSharedStorePatch(event, patch);
      expect(listener2.onPatch).toBeCalledWith(patch);
    });
  });
});