-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathhooks.test.js
More file actions
682 lines (617 loc) · 28.7 KB
/
hooks.test.js
File metadata and controls
682 lines (617 loc) · 28.7 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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
import 'CourseAuthoring/editors/setupEditorTest';
import { getConfig } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import * as keyUtils from '../../../generic/key-utils';
import { MockUseState } from '../../testUtils';
import * as tinyMCE from '../../data/constants/tinyMCE';
import { keyStore } from '../../utils';
import pluginConfig from './pluginConfig';
// This 'module' self-import hack enables mocking during tests.
// See src/editors/decisions/0005-internal-editor-testability-decisions.md. The whole approach to how hooks are tested
// should be re-thought and cleaned up to avoid this pattern.
// eslint-disable-next-line import/no-self-import
import * as module from './hooks';
jest.mock('react', () => ({
...jest.requireActual('react'),
createRef: jest.fn(val => ({ ref: val })),
useRef: jest.fn(val => ({ current: val })),
useEffect: jest.fn(),
useCallback: (cb, prereqs) => ({ cb, prereqs }),
}));
jest.mock('@edx/frontend-platform/auth', () => ({
getAuthenticatedHttpClient: jest.fn(),
}));
const state = new MockUseState(module);
const moduleKeys = keyStore(module);
let hook;
let output;
const editorImageWidth = 2022;
const editorImageHeight = 1619;
const mockNode = {
src: 'http://localhost:18000/asset-v1:TestX+Test01+Test0101+type@asset+block/DALL_E_2023-03-10.png',
alt: 'aLt tExt',
width: editorImageWidth,
height: editorImageHeight,
};
const initialContentHeight = 150;
const initialContentWidth = 100;
const mockNodeWithInitialContentDimensions = { ...mockNode, width: initialContentWidth, height: initialContentHeight };
const mockEditorWithSelection = { selection: { getNode: () => mockNode } };
const mockImage = {
displayName: 'DALL·E 2023-03-10.png',
contentType: 'image/png',
dateAdded: 1682009100000,
url: '/asset-v1:TestX+Test01+Test0101+type@asset+block@DALL_E_2023-03-10.png',
externalUrl: 'http://localhost:18000/asset-v1:TestX+Test01+Test0101+type@asset+block@DALL_E_2023-03-10.png',
portableUrl: '/static/DALL_E_2023-03-10.png',
thumbnail: '/asset-v1:TestX+Test01+Test0101+type@thumbnail+block@DALL_E_2023-03-10.jpg',
locked: false,
staticFullUrl: '/assets/courseware/v1/af2bf9ac70804e54c534107160a8e51e/asset-v1:TestX+Test01+Test0101+type@asset+block@DALL_E_2023-03-10.png',
id: 'asset-v1:TestX+Test01+Test0101+type@asset+block@DALL_E_2023-03-10.png',
width: initialContentWidth,
height: initialContentHeight,
};
const mockImages = {
[mockImage.id]: mockImage,
};
const mockEditorContentHtml = `
<p>
<img
src="/assets/courseware/v1/7b41573468a356ca8dc975158e388386/asset-v1:TestX+Test01+Test0101+type@asset+block/DALL_E_2023-03-10.png"
alt=""
width="${initialContentWidth}"
height="${initialContentHeight}">
</img>
</p>
`;
const baseAssetUrl = 'asset-v1:org+test+run+type@asset+block';
const mockImagesRef = { current: [mockImage] };
describe('TinyMceEditor hooks', () => {
beforeEach(() => {
jest.clearAllMocks();
mockImagesRef.current = [mockImage];
});
describe('state hooks', () => {
state.testGetter(state.keys.isImageModalOpen);
state.testGetter(state.keys.isSourceCodeModalOpen);
state.testGetter(state.keys.imageSelection);
});
describe('non-state hooks', () => {
beforeEach(() => { state.mock(); });
afterEach(() => { state.restore(); });
describe('detectImageMatchingError', () => {
it('should detect an error if the matchingImages array is empty', () => {
const matchingImages = [];
const tinyMceHTML = mockNode;
expect(module.detectImageMatchingError({ matchingImages, tinyMceHTML })).toBe(true);
});
it('should detect an error if the matchingImages array has more than one element', () => {
const matchingImages = [mockImage, mockImage];
const tinyMceHTML = mockNode;
expect(module.detectImageMatchingError({ matchingImages, tinyMceHTML })).toBe(true);
});
it('should detect an error if the image id does not match the tinyMceHTML src', () => {
const matchingImages = [{ ...mockImage, id: 'some-other-id' }];
const tinyMceHTML = mockNode;
expect(module.detectImageMatchingError({ matchingImages, tinyMceHTML })).toBe(true);
});
it('should detect an error if the image id matches the tinyMceHTML src, but width and height do not match', () => {
const matchingImages = [{ ...mockImage, width: 100, height: 100 }];
const tinyMceHTML = mockNode;
expect(module.detectImageMatchingError({ matchingImages, tinyMceHTML })).toBe(true);
});
it('should not detect any errors if id matches src, and width and height match', () => {
const matchingImages = [{ ...mockImage, width: mockNode.width, height: mockNode.height }];
const tinyMceHTML = mockNode;
expect(module.detectImageMatchingError({ matchingImages, tinyMceHTML })).toBe(false);
});
});
describe('setupCustomBehavior', () => {
test('It calls addButton and addToggleButton in the editor, but openModal is not called', () => {
const addButton = jest.fn();
const addIcon = jest.fn();
const addToggleButton = jest.fn();
const openImgModal = jest.fn();
const openSourceCodeModal = jest.fn();
const setImage = jest.fn();
const updateContent = jest.fn();
const editorType = 'expandable';
const lmsEndpointUrl = getConfig().LMS_BASE_URL;
const editor = {
ui: { registry: { addButton, addToggleButton, addIcon } },
on: jest.fn(),
};
const mockOpenModalWithImage = args => ({ openModalWithSelectedImage: args });
const expectedSettingsAction = mockOpenModalWithImage({ editor, setImage, openImgModal });
const toggleCodeFormatting = expect.any(Function);
const toggleLabelFormatting = expect.any(Function);
const setupCodeFormatting = expect.any(Function);
jest.spyOn(module, moduleKeys.openModalWithSelectedImage)
.mockImplementationOnce(mockOpenModalWithImage);
output = module.setupCustomBehavior({
editorType,
updateContent,
openImgModal,
openSourceCodeModal,
setImage,
lmsEndpointUrl,
})(editor);
expect(addIcon.mock.calls).toEqual([['textToSpeech', tinyMCE.textToSpeechIcon]]);
expect(addButton.mock.calls).toEqual([
[tinyMCE.buttons.imageUploadButton, { icon: 'image', tooltip: 'Add Image', onAction: openImgModal }],
[tinyMCE.buttons.editImageSettings, { icon: 'image', tooltip: 'Edit Image Settings', onAction: expectedSettingsAction }],
[tinyMCE.buttons.code, { text: 'HTML', tooltip: 'Source code', onAction: openSourceCodeModal }],
['customLabelButton', {
icon: 'textToSpeech',
text: 'Label',
tooltip: 'Apply a "Question" label to specific text, recognized by screen readers. Recommended to improve accessibility.',
onAction: toggleLabelFormatting,
}],
]);
expect(addToggleButton.mock.calls).toEqual([
[tinyMCE.buttons.codeBlock, {
icon: 'sourcecode', tooltip: 'Code Block', onAction: toggleCodeFormatting, onSetup: setupCodeFormatting,
}],
]);
expect(openImgModal).not.toHaveBeenCalled();
expect(editor.on).toHaveBeenCalled();
});
});
describe('parseContentForLabels', () => {
test('it calls getContent and updateQuestion for some content', () => {
const editor = { getContent: jest.fn(() => '<p><label>Some question label</label></p><p>some content <label>around a label</label> followed by more text</p><img src="/static/soMEImagEURl1.jpeg"/>') };
const updateContent = jest.fn();
const content = '<p><label>Some question label</label></p><p>some content </p><p><label>around a label</label></p><p> followed by more text</p><img src="/static/soMEImagEURl1.jpeg"/>';
module.parseContentForLabels({ editor, updateContent });
expect(editor.getContent).toHaveBeenCalled();
expect(updateContent).toHaveBeenCalledWith(content);
});
test('it calls getContent and updateQuestion for empty content', () => {
const editor = { getContent: jest.fn(() => '') };
const updateContent = jest.fn();
const content = '';
module.parseContentForLabels({ editor, updateContent });
expect(editor.getContent).toHaveBeenCalled();
expect(updateContent).toHaveBeenCalledWith(content);
});
});
describe('replaceStaticWithAsset', () => {
const initialContent = `<img src="/static/soMEImagEURl1.jpeg"/><a href="/assets/v1/${baseAssetUrl}/test.pdf">test</a><img src="/${baseAssetUrl}@correct.png" /><img src="/${baseAssetUrl}/correct.png" />`;
const learningContextId = 'course-v1:org+test+run';
const lmsEndpointUrl = getConfig().LMS_BASE_URL;
beforeEach(() => {
jest.clearAllMocks();
});
it('returns updated src for text editor to update content', async () => {
const expected = `<img src="/${baseAssetUrl}@soMEImagEURl1.jpeg"/><a href="/${baseAssetUrl}@test.pdf">test</a><img src="/${baseAssetUrl}@correct.png" /><img src="/${baseAssetUrl}@correct.png" />`;
const actual = await module.replaceStaticWithAsset({
initialContent,
learningContextId,
validateAssetUrl: false,
});
expect(actual).toEqual(expected);
});
it('returns updated src with absolute url for expandable editor to update content', async () => {
const expected = `<img src="${lmsEndpointUrl}/${baseAssetUrl}@soMEImagEURl1.jpeg"/><a href="${lmsEndpointUrl}/${baseAssetUrl}@test.pdf">test</a><img src="${lmsEndpointUrl}/${baseAssetUrl}@correct.png" /><img src="${lmsEndpointUrl}/${baseAssetUrl}@correct.png" />`;
const actual = await module.replaceStaticWithAsset({
initialContent,
editorType: 'expandable',
lmsEndpointUrl,
learningContextId,
validateAssetUrl: false,
});
expect(actual).toEqual(expected);
});
it('returns false when there are no srcs to update', async () => {
const content = '<div>Hello world!</div>';
const actual = await module.replaceStaticWithAsset({ initialContent: content, learningContextId });
expect(actual).toBeFalsy();
});
it('does not convert static URLs with subdirectories but converts direct static files', async () => {
const contentWithSubdirectory = '<img src="/static/images/placeholder-faculty.png"/><img src="/static/example.jpg"/>';
const expected = `<img src="/static/images/placeholder-faculty.png"/><img src="/${baseAssetUrl}@example.jpg"/>`;
const actual = await module.replaceStaticWithAsset({
initialContent: contentWithSubdirectory,
learningContextId,
validateAssetUrl: false,
});
expect(actual).toEqual(expected);
});
it('replaces multiple static assets in one content string', async () => {
const content = `
<img src="/static/a.png"/>
<img src="/static/b.png"/>
`;
const result = await module.replaceStaticWithAsset({
initialContent: content,
learningContextId,
validateAssetUrl: false,
});
expect(result).toBeTruthy();
});
it('validateAssetUrl success path replaces url', async () => {
getAuthenticatedHttpClient.mockReturnValue({
get: jest.fn(() => Promise.resolve({})),
});
const content = '<img src="/static/test.png"/>';
const result = await module.replaceStaticWithAsset({
initialContent: content,
learningContextId,
validateAssetUrl: true,
});
expect(result).toBeTruthy();
});
it('validateAssetUrl failure path keeps original content', async () => {
getAuthenticatedHttpClient.mockReturnValue({
get: jest.fn(() => Promise.reject(new Error('404'))),
});
const content = '<img src="/static/test.png"/>';
const result = await module.replaceStaticWithAsset({
initialContent: content,
learningContextId,
validateAssetUrl: true,
});
expect(result).toBeFalsy();
});
it('handles library keys correctly', async () => {
jest.spyOn(keyUtils, 'isLibraryKey').mockReturnValue(true);
const content = '<img src="/static/test.png"/>';
const result = await module.replaceStaticWithAsset({
initialContent: content,
learningContextId: 'lib:test',
validateAssetUrl: false,
});
expect(result).toContain('static/test.png');
});
it('returns false when asset already valid and no replacement needed', async () => {
const content = '<img src="/asset-v1:test+org+run+type@[email protected]"/>';
const result = await module.replaceStaticWithAsset({
initialContent: content,
learningContextId,
validateAssetUrl: false,
});
expect(result).toBe(false);
});
});
describe('setAssetToStaticUrl', () => {
it('returns content with updated img links', () => {
const editorValue = `<img src="/${baseAssetUrl}/soME_ImagE_URl1"/> <a href="/${baseAssetUrl}@soMEImagEURl">testing link</a>`;
const lmsEndpointUrl = getConfig().LMS_BASE_URL;
const content = module.setAssetToStaticUrl({ editorValue, lmsEndpointUrl });
expect(content).toEqual('<img src="/static/soME_ImagE_URl1"/> <a href="/static/soMEImagEURl">testing link</a>');
});
it('returns content with updated static img links', () => {
const editorValue = '<img src="static/goku.img"/> <a href="static/goku.img">testing link</a>';
const lmsEndpointUrl = getConfig().LMS_BASE_URL;
const content = module.setAssetToStaticUrl({ editorValue, lmsEndpointUrl });
expect(content).toEqual('<img src="/static/goku.img"/> <a href="/static/goku.img">testing link</a>');
});
});
describe('editorConfig', () => {
const props = {
editorContentHtml: null,
editorType: 'text',
lmsEndpointUrl: getConfig().LMS_BASE_URL,
studioEndpointUrl: getConfig().STUDIO_BASE_URL,
images: mockImagesRef,
isLibrary: false,
learningContextId: 'course+org+run',
};
const evt = 'fakeEvent';
const editor = 'myEditor';
const setupCustomBehavior = args => ({ setupCustomBehavior: args });
beforeEach(() => {
props.setEditorRef = jest.fn();
props.openImgModal = jest.fn();
props.openSourceCodeModal = jest.fn();
props.initializeEditor = jest.fn();
props.updateContent = jest.fn();
jest.spyOn(module, moduleKeys.setupCustomBehavior)
.mockImplementationOnce(setupCustomBehavior);
output = module.editorConfig(props);
});
describe('text editor plugins and toolbar', () => {
test('It configures plugins and toolbars correctly', () => {
const pluginProps = {
isLibrary: props.isLibrary,
editorType: props.editorType,
};
expect(output.init.plugins).toEqual(pluginConfig(pluginProps).plugins);
expect(output.init.imagetools_toolbar).toEqual(pluginConfig(pluginProps).imageToolbar);
expect(output.init.toolbar).toEqual(pluginConfig(pluginProps).toolbar);
Object.keys(pluginConfig(pluginProps).config).forEach(key => {
expect(output.init[key]).toEqual(pluginConfig(pluginProps).config[key]);
});
// Commented out as we investigate whether this is only needed for image proxy
// expect(output.init.imagetools_cors_hosts).toMatchObject([props.lmsEndpointUrl]);
});
});
describe('text editor plugins and toolbar for content library', () => {
test('It configures plugins and toolbars correctly', () => {
const pluginProps = {
isLibrary: true,
editorType: props.editorType,
};
output = module.editorConfig({ ...props, isLibrary: true });
expect(output.init.plugins).toEqual(pluginConfig(pluginProps).plugins);
expect(output.init.imagetools_toolbar).toEqual(pluginConfig(pluginProps).imageToolbar);
expect(output.init.toolbar).toEqual(pluginConfig(pluginProps).toolbar);
expect(output.init.quickbars_insert_toolbar).toEqual(pluginConfig(pluginProps).quickbarsInsertToolbar);
expect(output.init.quickbars_selection_toolbar).toEqual(pluginConfig(pluginProps).quickbarsSelectionToolbar);
Object.keys(pluginConfig(pluginProps).config).forEach(key => {
expect(output.init[key]).toEqual(pluginConfig(pluginProps).config[key]);
});
});
});
describe('problem editor question plugins and toolbar', () => {
test('It configures plugins and toolbars correctly', () => {
const pluginProps = {
isLibrary: props.isLibrary,
editorType: 'question',
placeholder: 'soMEtExT',
};
output = module.editorConfig({
...props,
editorType: 'question',
placeholder: 'soMEtExT',
});
expect(output.init.plugins).toEqual(pluginConfig(pluginProps).plugins);
expect(output.init.imagetools_toolbar).toEqual(pluginConfig(pluginProps).imageToolbar);
expect(output.init.toolbar).toEqual(pluginConfig(pluginProps).toolbar);
expect(output.init.quickbars_insert_toolbar).toEqual(pluginConfig(pluginProps).quickbarsInsertToolbar);
expect(output.init.quickbars_selection_toolbar).toEqual(pluginConfig(pluginProps).quickbarsSelectionToolbar);
Object.keys(pluginConfig(pluginProps).config).forEach(key => {
expect(output.init[key]).toEqual(pluginConfig(pluginProps).config[key]);
});
});
});
describe('expandable text area plugins and toolbar', () => {
test('It configures plugins, toolbars, and quick toolbars correctly', () => {
const pluginProps = {
isLibrary: props.isLibrary,
editorType: 'expandable',
placeholder: 'soMEtExT',
};
output = module.editorConfig({
...props,
editorType: 'expandable',
placeholder: 'soMEtExT',
});
expect(output.init.plugins).toEqual(pluginConfig(pluginProps).plugins);
expect(output.init.imagetools_toolbar).toEqual(pluginConfig(pluginProps).imageToolbar);
expect(output.init.toolbar).toEqual(pluginConfig(pluginProps).toolbar);
expect(output.init.quickbars_insert_toolbar).toEqual(pluginConfig(pluginProps).quickbarsInsertToolbar);
expect(output.init.quickbars_selection_toolbar).toEqual(pluginConfig(pluginProps).quickbarsSelectionToolbar);
Object.keys(pluginConfig(pluginProps).config).forEach(key => {
expect(output.init[key]).toEqual(pluginConfig(pluginProps).config[key]);
});
});
});
test('It creates an onInit which calls initializeEditor and setEditorRef', () => {
output.onInit(evt, editor);
expect(props.setEditorRef).toHaveBeenCalledWith(editor);
expect(props.initializeEditor).toHaveBeenCalled();
});
test('It sets the blockvalue to be empty string by default', () => {
expect(output.initialValue).toBe('');
});
test('It sets the blockvalue to be the blockvalue if nonempty', () => {
const editorContentHtml = 'SomE hTML content';
output = module.editorConfig({ ...props, editorContentHtml });
expect(output.initialValue).toBe(editorContentHtml);
});
it('calls setupCustomBehavior on setup', () => {
expect(output.init.setup).toEqual(
setupCustomBehavior({
editorType: props.editorType,
updateContent: props.updateContent,
openImgModal: props.openImgModal,
openSourceCodeModal: props.openSourceCodeModal,
setImage: props.setSelection,
images: mockImagesRef,
lmsEndpointUrl: props.lmsEndpointUrl,
learningContextId: props.learningContextId,
}),
);
});
});
describe('imgModalToggle', () => {
const hookKey = state.keys.isImageModalOpen;
beforeEach(() => {
hook = module.imgModalToggle();
});
test('isOpen: state value', () => {
expect(hook.isImgOpen).toEqual(state.stateVals[hookKey]);
});
test('openModal: calls setter with true', () => {
hook.openImgModal();
expect(state.setState[hookKey]).toHaveBeenCalledWith(true);
});
test('closeModal: calls setter with false', () => {
hook.closeImgModal();
expect(state.setState[hookKey]).toHaveBeenCalledWith(false);
});
});
describe('sourceCodeModalToggle', () => {
const editorRef = { current: { focus: jest.fn() } };
const hookKey = state.keys.isSourceCodeModalOpen;
beforeEach(() => {
hook = module.sourceCodeModalToggle(editorRef);
});
test('isOpen: state value', () => {
expect(hook.isSourceCodeOpen).toEqual(state.stateVals[hookKey]);
});
test('openModal: calls setter with true', () => {
hook.openSourceCodeModal();
expect(state.setState[hookKey]).toHaveBeenCalledWith(true);
});
test('closeModal: calls setter with false', () => {
hook.closeSourceCodeModal();
expect(state.setState[hookKey]).toHaveBeenCalledWith(false);
});
});
describe('openModalWithSelectedImage', () => {
const setImage = jest.fn();
const openImgModal = jest.fn();
let editor;
beforeEach(() => {
editor = { selection: { getNode: () => mockNodeWithInitialContentDimensions } };
module.openModalWithSelectedImage({
editor, images: mockImagesRef, openImgModal, setImage,
})();
});
afterEach(() => {
jest.clearAllMocks();
});
test('updates React state for selected image to be value stored in editor, adding dimensions from images ref', () => {
expect(setImage).toHaveBeenCalledWith({
externalUrl: mockNode.src,
altText: mockNode.alt,
width: mockImage.width,
height: mockImage.height,
});
});
test('opens image setting modal', () => {
expect(openImgModal).toHaveBeenCalled();
});
describe('when images cannot be successfully matched', () => {
beforeEach(() => {
editor = { selection: { getNode: () => mockNode } };
module.openModalWithSelectedImage({
editor, images: mockImagesRef, openImgModal, setImage,
})();
});
afterEach(() => {
jest.clearAllMocks();
});
test('updates React state for selected image to be value stored in editor, setting dimensions to null', () => {
expect(setImage).toHaveBeenCalledWith({
externalUrl: mockNode.src,
altText: mockNode.alt,
width: null,
height: null,
});
});
});
});
describe('selectedImage hooks', () => {
const val = { a: 'VaLUe' };
beforeEach(() => {
hook = module.selectedImage(val);
});
test('selection: state value', () => {
expect(hook.selection).toEqual(state.stateVals[state.keys.imageSelection]);
});
test('setSelection: setter for value', () => {
expect(hook.setSelection).toEqual(state.setState[state.keys.imageSelection]);
});
test('clearSelection: calls setter with null', () => {
expect(hook.setSelection).not.toHaveBeenCalled();
hook.clearSelection();
expect(hook.setSelection).toHaveBeenCalledWith(null);
});
});
describe('imageMatchRegex', () => {
it('should match a valid image url using "@" separators', () => {
expect(
'http://localhost:18000/asset-v1:TestX+Test01+Test0101+type@[email protected]',
).toMatch(module.imageMatchRegex);
});
it('should match a url including the keywords "asset-v1", "type", "block" in that order', () => {
expect(
'https://some.completely/made.up///url-with.?!keywords/asset-v1:[email protected]',
).toMatch(module.imageMatchRegex);
});
it('should not match a url excluding the keyword "asset-v1"', () => {
expect(
'https://some.completely/made.up///url-with.?!keywords/[email protected]',
).not.toMatch(module.imageMatchRegex);
});
it('should match an identifier including the keywords "asset-v1", "type", "block" using "/" separators', () => {
expect(
'asset-v1:TestX+Test01+Test0101+type/asset+block/image-name.png',
).toMatch(module.imageMatchRegex);
});
it('should capture values for the keys "asset-v1", "type", "block"', () => {
const match = 'asset-v1:TestX+Test01+Test0101+type/asset+block/image-name.png'.match(module.imageMatchRegex);
expect(match[1]).toBe('TestX+Test01+Test0101');
expect(match[2]).toBe('asset');
expect(match[3]).toBe('image-name.png');
});
});
describe('matchImageStringsByIdentifiers', () => {
it('should be true for an image url and identifier that have the same values for asset-v1, type, and block', () => {
const url = 'http://localhost:18000/asset-v1:TestX+Test01+Test0101+type@[email protected]';
const id = 'asset-v1:TestX+Test01+Test0101+type/asset+block/image-name.png';
expect(module.matchImageStringsByIdentifiers(url, id)).toBe(true);
});
it('should be false for an image url and identifier that have different values for block', () => {
const url = 'http://localhost:18000/asset-v1:TestX+Test01+Test0101+type@[email protected]';
const id = 'asset-v1:TestX+Test01+Test0101+type/asset+block/different-image-name.png';
expect(module.matchImageStringsByIdentifiers(url, id)).toBe(false);
});
it('should return null if it doesnt receive two strings as input', () => {
expect(module.matchImageStringsByIdentifiers(['a'], { b: 'c ' })).toBe(null);
});
it('should return undefined if the strings dont match the regex at all', () => {
expect(module.matchImageStringsByIdentifiers('wrong-url', 'blub')).toBe(undefined);
});
});
describe('addImagesAndDimensionsToRef', () => {
it('should add images to ref', () => {
const imagesRef = { current: null };
module.addImagesAndDimensionsToRef(
{
imagesRef,
images: mockImages,
editorContentHtml: mockEditorContentHtml,
},
);
expect(imagesRef.current).toEqual([mockImage]);
expect(imagesRef.current[0].width).toBe(initialContentWidth);
expect(imagesRef.current[0].height).toBe(initialContentHeight);
});
});
describe('getImageResizeHandler', () => {
const setImage = jest.fn();
it('sets image ref and state to new width', () => {
expect(mockImagesRef.current[0].width).toBe(initialContentWidth);
module.getImageResizeHandler({ editor: mockEditorWithSelection, imagesRef: mockImagesRef, setImage })();
expect(setImage).toHaveBeenCalledTimes(1);
expect(setImage).toHaveBeenCalledWith(expect.objectContaining({ width: editorImageWidth }));
expect(mockImagesRef.current[0].width).not.toBe(initialContentWidth);
expect(mockImagesRef.current[0].width).toBe(editorImageWidth);
});
});
describe('updateImageDimensions', () => {
const unchangedImg = {
id: 'asset-v1:TestX+Test01+Test0101+type@[email protected]',
width: 3,
height: 5,
};
const images = [
mockImage,
unchangedImg,
];
it('updates dimensions of correct image in images array', () => {
const { result, foundMatch } = module.updateImageDimensions({
images, url: mockNode.src, width: 123, height: 321,
});
const imageToHaveBeenUpdated = result.find(img => img.id === mockImage.id);
const imageToHaveBeenUnchanged = result.find(img => img.id === unchangedImg.id);
expect(imageToHaveBeenUpdated.width).toBe(123);
expect(imageToHaveBeenUpdated.height).toBe(321);
expect(imageToHaveBeenUnchanged.width).toBe(3);
expect(imageToHaveBeenUnchanged.height).toBe(5);
expect(foundMatch).toBe(true);
});
it('does not update images if id is not found', () => {
const { result, foundMatch } = module.updateImageDimensions({
images, url: 'not_found', width: 123, height: 321,
});
expect(result.find(img => img.width === 123 || img.height === 321)).toBeFalsy();
expect(foundMatch).toBe(false);
});
});
});
});