-
-
Notifications
You must be signed in to change notification settings - Fork 355
/
Copy pathrender.test.ts
672 lines (554 loc) · 25.3 KB
/
render.test.ts
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
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { getByTestId, getByText, waitFor } from '@testing-library/dom';
import userEvent from '@testing-library/user-event';
import { htmlToElement } from '../../src/dom_utils';
import { createTest, initComponent, shutdownTests } from '../tools';
describe('LiveController rendering Tests', () => {
afterEach(() => {
shutdownTests();
});
it('can re-render via an Ajax call', async () => {
const test = await createTest(
{ firstName: 'Ryan' },
(data: any) => `
<div ${initComponent(data)}>
<span>Name: ${data.firstName}</span>
<button data-action="live#$render">Reload</button>
</div>
`
);
test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change the data on the server so the template renders differently
data.firstName = 'Kevin';
});
getByText(test.element, 'Reload').click();
await waitFor(() => expect(test.element).toHaveTextContent('Name: Kevin'));
// data returned from the server is used for the new "data"
expect(test.component.valueStore.getOriginalProps()).toEqual({ firstName: 'Kevin' });
});
it('conserves the value of model field that was modified after a render request', async () => {
const test = await createTest(
{ title: 'greetings', comment: '' },
(data: any) => `
<div ${initComponent(data, { debounce: 1 })}>
<input data-model="title" value="${data.title}">
<!--
norender for comment to avoid triggering a 2nd Ajax call.
We want the first to finish, to see if it overwrites our value
-->
<textarea data-model="norender|comment">${data.comment}</textarea>
Title: "${data.title}"
Comment: "${data.comment}"
<button data-action="live#$render">Reload</button>
</div>
`
);
test.expectsAjaxCall()
// only the update title will be sent
.expectUpdatedData({ title: 'greetings!!' })
.delayResponse(100);
userEvent.type(test.queryByDataModel('title'), '!!');
setTimeout(() => {
// wait 10 ms (long enough for the shortened debounce to finish and the
// Ajax request to start) and then type into this field
userEvent.type(test.queryByDataModel('comment'), 'I had a great time');
}, 10);
// title model updated like normal
await waitFor(() => expect(test.element).toHaveTextContent('Title: "greetings!!"'));
// no re-render yet since "comment" was modified
expect(test.element).toHaveTextContent('Comment: ""');
// the field contains the text that was typed by the user after the first Ajax call triggered
expect((test.queryByDataModel('comment') as HTMLTextAreaElement).value).toEqual('I had a great time');
// the server returned comment as ''. However, this model WAS set
// during the last render, and that has not been taken into account yet.
// and so, like with the comment textarea, the client-side value is kept
expect(test.component.valueStore.getOriginalProps()).toEqual({
title: 'greetings!!',
// original props show it as blank
comment: '',
});
// but the valueStore has the latest value
expect(test.component.valueStore.get('comment')).toEqual('I had a great time');
// trigger render: the new comment data *will* now be sent
test.expectsAjaxCall()
.expectUpdatedData({ comment: 'I had a great time' })
.serverWillChangeProps((data: any) => {
// to be EXTRA complicated, the server will change the comment
// on the client, we should now recognize that the latest comment
// model data *was* sent (the <textarea> is no longer out-of-sync)
// and so it should accept the HTML from the server
data.comment = data.comment.toUpperCase();
});
getByText(test.element, 'Reload').click();
await waitFor(() => expect(test.element).toHaveTextContent('Comment: "I HAD A GREAT TIME"'));
expect((test.queryByDataModel('comment') as HTMLTextAreaElement).value).toEqual('I HAD A GREAT TIME');
});
it('keeps file input value after a render request', async () => {
const test = await createTest(
{},
() => `
<div ${initComponent({}, { debounce: 1 })}>
<input type="file" data-model="file">
<button data-action="live#$render">Reload</button>
</div>
`
);
const fileInput = test.element.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['content'], 'test.txt', { type: 'text/plain' });
Object.defineProperty(fileInput, 'files', {
value: [file],
writable: false,
});
// Checks that the file is correctly assigned before rendering
expect(fileInput.files).not.toBeNull();
expect(fileInput.files?.length).toBe(1);
expect(fileInput.files?.[0].name).toBe('test.txt');
// Simulates an AJAX request triggered by Live rendering
test.expectsAjaxCall()
.expectUpdatedData({})
.delayResponse(100);
getByText(test.element, 'Reload').click();
// Checks that the file is still present after rendering
await waitFor(() => {
expect(fileInput.files).not.toBeNull();
expect(fileInput.files?.length).toBe(1);
expect(fileInput.files?.[0].name).toBe('test.txt');
});
});
it('conserves the value of an unmapped field that was modified after a render request', async () => {
const test = await createTest(
{ title: 'greetings' },
(data: any) => `
<div ${initComponent(data, { debounce: 1 })}>
<input data-model="title" value="${data.title}">
<!-- An unmapped field -->
<textarea></textarea>
Title: "${data.title}"
<button data-action="live#$render">Reload</button>
</div>
`
);
test.expectsAjaxCall().expectUpdatedData({ title: 'greetings!!' }).delayResponse(100);
userEvent.type(test.queryByDataModel('title'), '!!');
setTimeout(() => {
// wait 10 ms (long enough for the shortened debounce to finish and the
// Ajax request to start) and then type into this field
userEvent.type(
test.element.querySelector('textarea') as HTMLTextAreaElement,
'typing after the request starts'
);
}, 10);
// title model updated like normal
await waitFor(() => expect(test.element).toHaveTextContent('Title: "greetings!!"'));
// field *still* contains the text that was typed by the user after the Ajax call started
expect((test.element.querySelector('textarea') as HTMLTextAreaElement).value).toEqual(
'typing after the request starts'
);
// make a 2nd request
test.expectsAjaxCall().expectUpdatedData({ title: 'greetings!! Yay!' }).delayResponse(100);
userEvent.type(test.queryByDataModel('title'), ' Yay!');
// title model updated like normal
await waitFor(() => expect(test.element).toHaveTextContent('Title: "greetings!! Yay!"'));
// field *still* contains modified text
expect((test.element.querySelector('textarea') as HTMLTextAreaElement).value).toEqual(
'typing after the request starts'
);
});
it('conserves cursor position of active model element', async () => {
const test = await createTest(
{ name: '' },
(data) => `
<div ${initComponent(data)}>
<input data-model="name" class="anything">
</div>
`
);
test.expectsAjaxCall().expectUpdatedData({ name: 'Hello' });
const input = test.queryByDataModel('name') as HTMLInputElement;
userEvent.type(input, 'Hello');
userEvent.keyboard('{ArrowLeft}{ArrowLeft}');
await test.component.render();
// the cursor position should be preserved
expect(input.selectionStart).toBe(3);
userEvent.type(input, '!');
expect(input.value).toBe('Hel!lo');
});
it('uses the new value of an unmapped field that was NOT modified even if active', async () => {
const test = await createTest(
{ title: 'greetings' },
(data: any) => `
<div ${initComponent(data)}>
<!-- An unmapped field -->
<input value="${data.title}">
Title: "${data.title}"
</div>
`
);
test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change the data on the server so the template renders differently
data.title = 'Hello';
});
const input = test.element.querySelector('input') as HTMLInputElement;
// focus the input, but don't change it
userEvent.type(input, '');
await test.component.render();
expect(input.value).toEqual('Hello');
});
it('does not render over elements with data-live-ignore', async () => {
const test = await createTest(
{ firstName: 'Ryan' },
(data: any) => `
<div ${initComponent(data)}>
<div data-live-ignore>Inside Ignore Name: <span>${data.firstName}</span></div>
Outside Ignore Name: ${data.firstName}
<button data-action="live#$render">Reload</button>
</div>
`
);
// imitate some JavaScript changing this element
test.element.querySelector('span')?.setAttribute('data-foo', 'bar');
test.element.appendChild(htmlToElement('<div data-live-ignore>I should not be removed</div>'));
test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change the data on the server so the template renders differently
data.firstName = 'Kevin';
});
getByText(test.element, 'Reload').click();
await waitFor(() => expect(test.element).toHaveTextContent('Outside Ignore Name: Kevin'));
const ignoreElement = test.element.querySelector('div[data-live-ignore]');
expect(ignoreElement).not.toBeNull();
expect(ignoreElement?.outerHTML).toEqual(
'<div data-live-ignore="">Inside Ignore Name: <span data-foo="bar">Ryan</span></div>'
);
expect(test.element.innerHTML).toContain('I should not be removed');
});
it('if id changes, data-live-ignore elements ARE re-rendered', async () => {
const test = await createTest(
{ firstName: 'Ryan', containerId: 'original' },
(data: any) => `
<div ${initComponent(data)}>
<div id="${data.containerId}">
<div data-live-ignore>Inside Ignore Name: <span>${data.firstName}</span></div>
</div>
Outside Ignore Name: ${data.firstName}
<button data-action="live#$render">Reload</button>
</div>
`
);
test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change the data on the server so the template renders differently
data.firstName = 'Kevin';
data.containerId = 'updated';
});
getByText(test.element, 'Reload').click();
await waitFor(() => expect(test.element).toHaveTextContent('Outside Ignore Name: Kevin'));
const ignoreElement = test.element.querySelector('div[data-live-ignore]');
expect(ignoreElement).not.toBeNull();
// check that even the ignored element re-rendered
expect(ignoreElement?.outerHTML).toEqual(
'<div data-live-ignore="">Inside Ignore Name: <span>Kevin</span></div>'
);
});
it('overwrites HTML instead of morph with data-skip-morph', async () => {
const test = await createTest(
{ firstName: 'Ryan' },
(data: any) => `
<div ${initComponent(data)}>
<div data-skip-morph data-name="${data.firstName}">Inside Skip Name: <span data-testid="inside-skip-morph">${data.firstName}</span></div>
Outside Skip Name: ${data.firstName}
<button data-action="live#$render">Reload</button>
</div>
`
);
const spanBefore = getByTestId(test.element, 'inside-skip-morph');
expect(spanBefore).toHaveTextContent('Ryan');
test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change the data on the server so the template renders differently
data.firstName = 'Kevin';
});
getByText(test.element, 'Reload').click();
await waitFor(() => expect(test.element).toHaveTextContent('Outside Skip Name: Kevin'));
// make sure the outer element is still updated
const skipElement = test.element.querySelector('div[data-skip-morph]');
if (!(skipElement instanceof HTMLElement)) {
throw new Error('skipElement is not an HTMLElement');
}
expect(skipElement.dataset.name).toEqual('Kevin');
const spanAfter = getByTestId(test.element, 'inside-skip-morph');
expect(spanAfter).toHaveTextContent('Kevin');
// but it is not just a mutation of the original element
expect(spanAfter).not.toBe(spanBefore);
});
it('cancels a re-render if the page is navigating away', async () => {
const test = await createTest(
{ greeting: 'aloha!' },
(data: any) => `
<div ${initComponent(data)}>${data.greeting}</div>
`
);
test.expectsAjaxCall()
.serverWillChangeProps((data) => {
data.greeting = 'Hello';
})
.delayResponse(100);
const promise = test.component.render();
// trigger disconnect
test.element.removeAttribute('data-controller');
// wait for the fetch to finish
await promise;
// the re-render should not have happened
expect(test.element).not.toHaveTextContent('Hello');
});
it('renders if the page is navigating away and back', async () => {
const test = await createTest(
{ greeting: 'aloha!' },
(data: any) => `
<div ${initComponent(data)}>${data.greeting}</div>
`
);
test.expectsAjaxCall()
.serverWillChangeProps((data) => {
data.greeting = 'Hello';
})
.delayResponse(100);
const promise = test.component.render();
// trigger controller disconnect
test.element.removeAttribute('data-controller');
// wait for the fetch to finish
await promise;
expect(test.element).toHaveTextContent('aloha!');
// trigger connect
test.element.setAttribute('data-controller', 'live');
test.expectsAjaxCall()
.serverWillChangeProps((data) => {
data.greeting = 'Hello2';
})
.delayResponse(100);
await test.component.render();
// the re-render should have happened
expect(test.element).toHaveTextContent('Hello2');
});
it('waits for the previous request to finish & batches changes', async () => {
const test = await createTest(
{ title: 'greetings', contents: '' },
(data: any) => `
<div ${initComponent(data, { debounce: 1 })}>
<input data-model="title" value="${data.title}">
<textarea data-model="contents">${data.contents}</textarea>
Title: "${data.title}"
<button data-action="live#$render">Reload</button>
</div>
`
);
// expect the initial Reload request, but delay it
test.expectsAjaxCall().delayResponse(100);
getByText(test.element, 'Reload').click();
setTimeout(() => {
// wait 10 ms (long enough for the shortened debounce to finish and the
// Ajax request to start) and then type into the fields
userEvent.type(test.queryByDataModel('title'), '!!!');
userEvent.type(test.queryByDataModel('contents'), 'Welcome to our test!');
// NOW we're expecting th 2nd request
test.expectsAjaxCall()
// only 1 request, both new pieces of data sent at once
.expectUpdatedData({
title: 'greetings!!!',
contents: 'Welcome to our test!',
});
}, 10);
await waitFor(() => expect(test.element).toHaveTextContent('Title: "greetings!!!"'));
});
it('batches re-render requests together that occurred during debounce', async () => {
const test = await createTest(
{ title: 'greetings', contents: '' },
(data: any) => `
<div ${initComponent(data, { debounce: 50 })}>
<input data-model="title" value="${data.title}">
<textarea data-model="contents">${data.contents}</textarea>
Title: "${data.title}"
<button data-action="live#$render">Reload</button>
</div>
`
);
// type: 50ms debounce will begin
userEvent.type(test.queryByDataModel('title'), ' to you');
setTimeout(() => {
// wait 40 ms: not long enough for debounce, then modify this field
userEvent.type(test.queryByDataModel('contents'), 'Welcome to our test!');
// the ONE request will not start until 50ms (debounce) from now
// delay 40 ms before we start to expect it
setTimeout(() => {
// just one request should be made
test.expectsAjaxCall().expectUpdatedData({
title: 'greetings to you',
contents: 'Welcome to our test!',
});
}, 40);
}, 40);
await waitFor(() => expect(test.element).toHaveTextContent('Title: "greetings to you"'));
});
it('waits for the rendering process of previous request to finish before starting a new one', async () => {
const test = await createTest(
{
title: 'greetings',
contents: '',
},
(data: any) => `
<div ${initComponent(data)}>
<input data-model='title' value='${data.title}'>
Title: "${data.title}"
<button data-action='live#$render'>Reload</button>
</div>
`
);
let didSecondRenderStart = false;
let secondRenderStartedAt = 0;
test.component.on('render:started', () => {
if (didSecondRenderStart) {
return;
}
didSecondRenderStart = true;
test.component.on('loading.state:started', () => {
secondRenderStartedAt = Date.now();
});
test.expectsAjaxCall();
test.component.render();
});
let firstRenderFinishedAt = 0;
test.component.on('render:finished', () => {
// set the finish time for the first render only
if (firstRenderFinishedAt === 0) {
firstRenderFinishedAt = Date.now();
}
// the sleep guarantees that if the 2nd request was correctly
// delayed, its start time will be at least 10ms after the first
// render finished. Without this, even if the 2nd request is
// correctly delayed, the "first render finish" and "second render
// start" times could be the same, because no time has passed.
const sleep = (milliseconds: number) => {
const startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliseconds);
};
sleep(10);
});
test.expectsAjaxCall();
await test.component.render();
await waitFor(() => expect(didSecondRenderStart).toBe(true));
await waitFor(() => expect(firstRenderFinishedAt).not.toBe(0));
await waitFor(() => expect(secondRenderStartedAt).not.toBe(0));
expect(secondRenderStartedAt).toBeGreaterThan(firstRenderFinishedAt);
});
it('can update svg', async () => {
const test = await createTest(
{ text: 'SVG' },
(data: any) => `
<div ${initComponent(data)}>
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200">
<text x="150" y="125" font-size="60" text-anchor="middle" fill="red">${data.text}</text>
</svg>
<button data-action="live#$render">Reload</button>
</div>
`
);
test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change the data on the server so the template renders differently
data.text = '123';
});
getByText(test.element, 'Reload').click();
await waitFor(() => expect(test.element).toHaveTextContent('123'));
});
it('can update html containing svg', async () => {
const test = await createTest(
{ text: 'Hello' },
(data: any) => `
<div ${initComponent(data)}>
${data.text}
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="200">
<text x="150" y="125" font-size="60" text-anchor="middle" fill="red">SVG</text>
</svg>
<button data-action="live#$render">Reload</button>
</div>
`
);
test.expectsAjaxCall().serverWillChangeProps((data: any) => {
// change the data on the server so the template renders differently
data.text = '123';
});
getByText(test.element, 'Reload').click();
await waitFor(() => expect(test.element).toHaveTextContent('123'));
});
it('can understand comment in the response', async () => {
const test = await createTest(
{ season: 'summer' },
(data: any) => `
<!-- messy comment -->
<div ${initComponent(data)}>
The season is: ${data.season}
</div>
`
);
test.expectsAjaxCall().serverWillChangeProps((data) => {
data.season = 'autumn';
});
await test.component.render();
// verify the component *did* render ok
expect(test.element).toHaveTextContent('The season is: autumn');
});
it('select the placeholder option tag after render', async () => {
const test = await createTest(
{},
(data: any) => `
<div ${initComponent(data)}>
<form>
<select id="select_option_1">
<option value="">Choose option 1</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="select_option_2">
<option value="">Choose option 2</option>
<option value="1_1">One - One</option>
<option value="1_2">One - Two</option>
<option value="2_1">Two - One</option>
<option value="2_2">Two - Two</option>
<option value="3_1">Three - One</option>
<option value="3_2">Three - Two</option>
</select>
</form>
</div>
`
);
test.expectsAjaxCall().willReturn(
(data) => `
<div ${initComponent(data)}>
<form>
<select id="select_option_1">
<option value="">Choose option 1</option>
<option value="1">One</option>
<option value="2" selected>Two</option>
<option value="3">Three</option>
</select>
<select id="select_option_2">
<option value="">Choose option 2</option>
<option value="2_1">Two - One</option>
<option value="2_2">Two - Two</option>
</select>
</form>
</div>
`
);
await test.component.render();
const selectOption2 = test.element.querySelector('#select_option_2') as HTMLSelectElement;
// verify the placeholder of the select option 2 is selected
expect(selectOption2.children[0].selected).toBe(true);
// verify the selectedIndex of the select option 2 is 0
expect(selectOption2.selectedIndex).toBe(0);
});
});