-
Notifications
You must be signed in to change notification settings - Fork 756
Expand file tree
/
Copy pathapp-spec.tsx
More file actions
528 lines (443 loc) · 17.4 KB
/
app-spec.tsx
File metadata and controls
528 lines (443 loc) · 17.4 KB
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import { mocked } from 'jest-mock';
import * as semver from 'semver';
import { EditorValues, MAIN_JS, SetFiddleOptions } from '../../src/interfaces';
import { App } from '../../src/renderer/app';
import { EditorMosaic, EditorPresence } from '../../src/renderer/editor-mosaic';
import { defaultDark, defaultLight } from '../../src/themes-defaults';
import { createEditorValues } from '../mocks/mocks';
import { waitFor } from '../utils';
global.fetch = window.fetch = jest.fn();
jest.mock('../../src/renderer/components/header', () => ({
Header: () => 'Header;',
}));
jest.mock('../../src/renderer/components/dialogs', () => ({
Dialogs: () => 'Dialogs;',
}));
jest.mock('../../src/renderer/components/output-editors-wrapper', () => ({
OutputEditorsWrapper: () => 'OutputEditorsWrapper;',
}));
describe('App component', () => {
let app: App;
beforeAll(() => {
document.body.innerHTML = '<div id="app" />';
});
beforeEach(() => {
mocked(window.ElectronFiddle.getTemplate).mockResolvedValue({
[MAIN_JS]: '// content',
});
mocked(window.ElectronFiddle.readThemeFile).mockResolvedValue(defaultDark);
mocked(window.ElectronFiddle.getReleasedVersions).mockReturnValue([]);
mocked(window.ElectronFiddle.getLatestStable).mockReturnValue(
semver.parse('24.0.0')!,
);
const { app: appMock } = window;
const { electronTypes, fileManager, remoteLoader, runner, state } = appMock;
app = new App();
jest.spyOn(app.state, 'downloadVersion').mockResolvedValue(undefined);
Object.assign(app, {
electronTypes,
fileManager,
remoteLoader,
runner,
state,
});
window.app = app;
state.editorMosaic.set({ [MAIN_JS]: '// content' });
state.editorMosaic.files.set(MAIN_JS, EditorPresence.Pending);
});
describe('setup()', () => {
it('renders the app', async () => {
jest.useFakeTimers();
const result = (await app.setup()) as HTMLDivElement;
jest.runAllTimers();
expect(result.innerHTML).toBe('Header;OutputEditorsWrapper;Dialogs;');
jest.useRealTimers();
});
it('updates electronTypes when state.version changes', async () => {
const { state } = app;
// test that electronTypes is set during app.setup
const spy = jest.spyOn(app.electronTypes, 'setVersion');
await app.setup();
expect(spy).toHaveBeenLastCalledWith(state.currentElectronVersion);
expect(spy).toHaveBeenCalledTimes(1);
// set up the next test: change state.version to a different version
const version = Object.values(state.versions).shift()!;
expect(state.currentElectronVersion).not.toStrictEqual(version);
await state.setVersion(version.version);
expect(state.currentElectronVersion).toStrictEqual(version);
// test that electronTypes was updated when state.version changed
expect(spy).toHaveBeenLastCalledWith(state.currentElectronVersion);
expect(spy).toHaveBeenCalledTimes(2);
});
});
describe('openFiddle()', () => {
it('understands gists', async () => {
const { fetchGistAndLoad } = app.remoteLoader;
mocked(fetchGistAndLoad).mockResolvedValue(true);
const gistId = '8c5fc0c6a5153d49b5a4a56d3ed9da8f';
await app.openFiddle({ gistId });
expect(fetchGistAndLoad).toHaveBeenCalledWith(gistId);
});
it('understands files', async () => {
const { openFiddle } = app.fileManager;
mocked(openFiddle).mockResolvedValueOnce(undefined);
const filePath = '/fake/path';
const files = { [MAIN_JS]: 'foo' };
await app.openFiddle({ localFiddle: { filePath, files } });
expect(openFiddle).toHaveBeenCalledWith(filePath, files);
});
});
describe('getEditorValues()', () => {
it('gets values', async () => {
const values = createEditorValues();
jest.spyOn(app.state.editorMosaic, 'values').mockReturnValue(values);
const b = await app.getEditorValues({});
expect(b).toStrictEqual(values);
});
});
describe('replaceFiddle()', () => {
let editorValues: EditorValues;
beforeEach(() => {
editorValues = createEditorValues();
});
it('sets editor values and source info', async () => {
const filePath = '/dev/urandom';
const gistId = '129fe1ed16f97c5b65e86795c7aa9762';
const templateName = 'clipboard';
await app.replaceFiddle(editorValues, {
localFiddle: { filePath, files: {} },
templateName,
gistId,
});
expect(app.state.gistId).toBe(gistId);
expect(app.state.templateName).toBe(templateName);
expect(app.state.localPath).toBe(filePath);
expect(app.state.editorMosaic.isEdited).toBe(false);
});
it.each([
{ gistId: 'ed44613269be4b1eff79' },
{ localFiddle: { filePath: '/etc/passwd', files: {} } },
{ templateName: 'clipboard' },
])(
'updates appState when called with %o',
async (opts: SetFiddleOptions) => {
await app.replaceFiddle(editorValues, opts);
const { state } = app;
expect(Boolean(state.gistId)).toBe(Boolean(opts.gistId));
expect(Boolean(state.templateName)).toBe(Boolean(opts.templateName));
expect(Boolean(state.localPath)).toBe(
Boolean(opts.localFiddle?.filePath),
);
},
);
describe('prompting to confirm replacing an unsaved fiddle', () => {
// make a second fiddle that differs from the first
const editorValues2: EditorValues = { [MAIN_JS]: '// hello world' };
async function testDialog(
confirm: boolean,
expectedValues: EditorValues,
) {
// load up a fiddle...
const localPath = '/etc/passwd';
const gistId = '2c24ecd147c9c28c9b2d0cf738d4993a';
await app.replaceFiddle(editorValues, {
localFiddle: { filePath: localPath, files: {} },
});
expect(app.state.gistId).toBeFalsy();
expect(app.state.localPath).toBe(localPath);
// ...mark it as edited so a confirm dialog will appear before replacing
app.state.editorMosaic.isEdited = true;
app.state.showConfirmDialog = jest.fn().mockResolvedValue(confirm);
// now try to replace
await app.replaceFiddle(editorValues2, { gistId });
expect(app.state.showConfirmDialog).toHaveBeenCalled();
expect(await app.getEditorValues()).toStrictEqual(expectedValues);
}
it('does not replace the fiddle if not confirmed', async () => {
await testDialog(false, editorValues);
});
it('replaces the fiddle if confirmed', async () => {
await testDialog(true, editorValues2);
});
});
});
describe('setupResizeListener()', () => {
it('attaches to the handler', () => {
window.addEventListener = jest.fn();
app.setupResizeListener();
expect(window.addEventListener).toHaveBeenCalledWith(
'resize',
expect.anything(),
);
});
});
describe('loadTheme()', () => {
it(`adds the current theme's css to the document`, async () => {
document.head!.innerHTML = "<style id='fiddle-theme'></style>";
await app.loadTheme('');
expect(document.head!.innerHTML).toEqual(
`<style id="fiddle-theme">
html, body {
--foreground-1: #9feafa;
--foreground-2: #8ac7d6;
--foreground-3: #608291;
--background-4: #21232d;
--background-3: #2c2e3b;
--background-2: #1d2427;
--background-1: #2f3241;
--border-color-2: #1e2527;
--border-color-1: #5c5f71;
--border: 1px solid var(--border-color-1);
--button-text-color: #000;
--text-color-1: #ffffff;
--text-color-2: #1e2527;
--text-color-3: #dcdcdc;
--error-color: #df3434;
--fonts-common: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
</style>`.replace(/ /gm, ''),
);
});
it('removes the dark theme option if required', async () => {
mocked(window.ElectronFiddle.readThemeFile).mockResolvedValue(
defaultLight,
);
document.body.classList.add('bp3-dark');
await app.loadTheme('defaultLight');
expect(document.body.classList.value).toBe('');
});
it('adds the dark theme option if required', async () => {
await app.loadTheme('custom-dark');
expect(document.body.classList.value).toBe('bp3-dark');
});
it('sets native theme', async () => {
app.state.isUsingSystemTheme = false;
mocked(window.ElectronFiddle.readThemeFile).mockResolvedValue(
defaultLight,
);
await app.loadTheme('defaultLight');
expect(window.ElectronFiddle.setNativeTheme).toHaveBeenCalledWith(
'light',
);
mocked(window.ElectronFiddle.readThemeFile).mockResolvedValue(
defaultDark,
);
await app.loadTheme('custom-dark');
expect(window.ElectronFiddle.setNativeTheme).toHaveBeenCalledWith('dark');
});
});
describe('setupThemeListeners()', () => {
const addEventListenerMock = jest.fn();
beforeEach(() => {
// matchMedia mock
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: addEventListenerMock,
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
});
describe('isUsingSystemTheme reaction', () => {
beforeEach(() => {
window.ElectronFiddle.setNativeTheme = jest.fn();
});
it('ignores system theme changes when not isUsingSystemTheme', () => {
app.state.isUsingSystemTheme = true;
app.setupThemeListeners();
app.state.isUsingSystemTheme = false;
expect(app.state.setTheme).not.toHaveBeenCalled();
});
it('sets theme according to system when isUsingSystemTheme', () => {
app.setupThemeListeners();
// isUsingSystemTheme and prefersDark
app.state.isUsingSystemTheme = false;
mocked(window.matchMedia).mockReturnValue({
matches: true,
} as MediaQueryList);
app.state.isUsingSystemTheme = true;
expect(app.state.setTheme).toHaveBeenCalledWith(defaultDark.file);
// isUsingSystemTheme and not prefersDark
app.state.isUsingSystemTheme = false;
mocked(window.matchMedia).mockReturnValue({
matches: false,
} as MediaQueryList);
app.state.isUsingSystemTheme = true;
expect(app.state.setTheme).toHaveBeenCalledWith(defaultLight.file);
});
it('sets native theme to system', () => {
app.state.isUsingSystemTheme = false;
app.setupThemeListeners();
app.state.isUsingSystemTheme = true;
expect(window.ElectronFiddle.setNativeTheme).toHaveBeenCalledWith(
'system',
);
});
});
describe('prefers-color-scheme event listener', () => {
it('adds an event listener to the "change" event', () => {
app.setupThemeListeners();
expect(addEventListenerMock).toHaveBeenCalledWith(
'change',
expect.anything(),
);
});
it('does nothing if not isUsingSystemTheme', () => {
app.setupThemeListeners();
const callback = addEventListenerMock.mock.calls[0][1];
app.state.isUsingSystemTheme = false;
callback({ matches: true });
expect(app.state.setTheme).not.toHaveBeenCalled();
});
it('sets dark theme if isUsingSystemTheme and prefers dark', () => {
app.setupThemeListeners();
const callback = addEventListenerMock.mock.calls[0][1];
app.state.isUsingSystemTheme = true;
callback({ matches: true });
expect(app.state.setTheme).toHaveBeenCalledWith(defaultDark.file);
});
it('sets light theme if isUsingSystemTheme and not prefers dark', () => {
app.setupThemeListeners();
const callback = addEventListenerMock.mock.calls[0][1];
app.state.isUsingSystemTheme = true;
callback({ matches: false });
expect(app.state.setTheme).toHaveBeenCalledWith(defaultLight.file);
});
});
});
describe('setupTitleListeners()', () => {
it('updates the document title when state.title changes', async () => {
const title = 'Hello, World!';
app.setupTitleListeners();
(app.state.title as any) = title;
await waitFor(() => document.title?.length > 0);
expect(document.title).toMatch(title);
});
});
describe('setupProtocolListeners()', () => {
it('handles registering new versions', () => {
const addEventListenerMock = window.ElectronFiddle
.addEventListener as any;
addEventListenerMock.mockClear();
app.setupProtocolListeners();
expect(addEventListenerMock).toHaveBeenCalledWith(
'register-local-version',
expect.anything(),
);
const callback = addEventListenerMock.mock.calls[0][1];
const addVersion = {
name: 'new-version',
path: '/version/build/path',
version: '123.0.0-local',
};
callback(addVersion);
expect(app.state.addLocalVersion).toHaveBeenCalledWith({
name: addVersion.name,
localPath: addVersion.path,
version: addVersion.version,
});
expect(app.state.setVersion).toHaveBeenCalledWith(addVersion.version);
});
});
describe('prompting to confirm replacing an unsaved fiddle', () => {
// make a second fiddle that differs from the first
const editorValues = createEditorValues();
const editorValues2: EditorValues = { [MAIN_JS]: '// hello world' };
let editorMosaic: EditorMosaic;
beforeEach(() => {
({ editorMosaic } = app.state);
});
async function testDialog(confirm: boolean) {
const localPath = '/etc/passwd';
const gistId = '2c24ecd147c9c28c9b2d0cf738d4993a';
// load up a fiddle...
await app.replaceFiddle(editorValues, {
localFiddle: { filePath: localPath, files: {} },
});
expect(app.state.gistId).toBeFalsy();
expect(app.state.localPath).toBe(localPath);
// ...mark it as edited so that trying a confirm dialog
// will be triggered when we try to replace it
editorMosaic.isEdited = true;
// set up a reaction to confirm the replacement
// when it happens
app.state.showConfirmDialog = jest.fn().mockResolvedValueOnce(confirm);
// now try to replace
await app.replaceFiddle(editorValues2, { gistId });
expect(app.state.showConfirmDialog).toHaveBeenCalled();
}
it('does not replace the fiddle if not confirmed', async () => {
const setSpy = jest.spyOn(app.state.editorMosaic, 'set').mockReset();
await testDialog(false);
expect(setSpy).toHaveBeenCalledTimes(1);
});
it('replaces the fiddle if confirmed', async () => {
const setSpy = jest.spyOn(app.state.editorMosaic, 'set').mockReset();
await testDialog(true);
expect(setSpy).toHaveBeenCalledTimes(2);
});
});
describe('prompting to confirm exiting an unsaved fiddle', () => {
beforeEach(() => {
// setup: mock close & setNativeTheme
window.close = jest.fn();
window.ElectronFiddle.setNativeTheme = jest.fn();
app.setupUnloadListeners();
});
it('can close the window if user accepts the dialog', async () => {
app.state.showConfirmDialog = jest.fn().mockResolvedValueOnce(true);
// expect the app to be watching for exit if the fiddle is edited
app.state.editorMosaic.isEdited = true;
expect(window.onbeforeunload).toBeTruthy();
const e = {
returnValue: Boolean,
};
window.onbeforeunload!(e as any);
expect(e.returnValue).toBe(false);
await waitFor(
() => mocked(window.ElectronFiddle.showWindow).mock.calls.length > 0,
);
expect(window.close).toHaveBeenCalled();
});
it('can close the app after user accepts dialog', async () => {
app.state.isQuitting = true;
app.state.showConfirmDialog = jest.fn().mockResolvedValueOnce(true);
// expect the app to be watching for exit if the fiddle is edited
app.state.editorMosaic.isEdited = true;
expect(window.onbeforeunload).toBeTruthy();
const e = {
returnValue: Boolean,
};
window.onbeforeunload!(e as any);
expect(e.returnValue).toBe(false);
await waitFor(
() => mocked(window.ElectronFiddle.showWindow).mock.calls.length > 0,
);
expect(window.ElectronFiddle.confirmQuit).toHaveBeenCalled();
expect(window.close).toHaveBeenCalledTimes(1);
});
it('does nothing if user cancels the dialog', async () => {
app.state.isQuitting = true;
app.state.showConfirmDialog = jest.fn().mockResolvedValueOnce(false);
// expect the app to be watching for exit if the fiddle is edited
app.state.editorMosaic.isEdited = true;
expect(window.onbeforeunload).toBeTruthy();
const e = {
returnValue: Boolean,
};
window.onbeforeunload!(e as any);
expect(e.returnValue).toBe(false);
await waitFor(
() => mocked(window.ElectronFiddle.showWindow).mock.calls.length > 0,
);
expect(window.close).not.toHaveBeenCalled();
expect(!app.state.isQuitting);
});
});
});