-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathindex.spec.js
More file actions
867 lines (736 loc) · 30.5 KB
/
index.spec.js
File metadata and controls
867 lines (736 loc) · 30.5 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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
import { createElement } from 'lwc';
import Container from 'x/container';
import Escape from 'x/escape';
import MultipleStyles from 'x/multipleStyles';
import SvgNs from 'x/svgNs';
import Table from 'x/table';
import SvgPath from 'x/svgPath';
import SvgPathInDiv from 'x/svgPathInDiv';
import SvgPathInG from 'x/svgPathInG';
import StaticUnsafeTopLevel from 'x/staticUnsafeTopLevel';
import OnlyEventListener from 'x/onlyEventListener';
import OnlyEventListenerChild from 'x/onlyEventListenerChild';
import OnlyEventListenerGrandchild from 'x/onlyEventListenerGrandchild';
import ListenerStaticWithUpdates from 'x/listenerStaticWithUpdates';
import DeepListener from 'x/deepListener';
import Comments from 'x/comments';
import PreserveComments from 'x/preserveComments';
import Attribute from 'x/attribute';
import DeepAttribute from 'x/deepAttribute';
import IframeOnload from 'x/iframeOnload';
import WithKey from 'x/withKey';
import Text from 'x/text';
import TableWithExpression from 'x/tableWithExpressions';
import TextWithoutPreserveComments from 'x/textWithoutPreserveComments';
import TextWithPreserveComments from 'x/textWithPreserveComments';
import { jasmine } from '../../helpers/jasmine.js';
import { LOWERCASE_SCOPE_TOKENS } from '../../helpers/constants.js';
import { extractDataIds } from '../../helpers/utils.js';
describe.skipIf(process.env.NATIVE_SHADOW)('Mixed mode for static content', () => {
['native', 'synthetic'].forEach((firstRenderMode) => {
it(`should set the tokens for synthetic shadow when it renders first in ${firstRenderMode}`, () => {
const elm = createElement('x-container', { is: Container });
elm.syntheticFirst = firstRenderMode === 'synthetic';
document.body.appendChild(elm);
const syntheticMode = elm.shadowRoot
.querySelector('x-component')
.shadowRoot.querySelector('div');
const nativeMode = elm.shadowRoot
.querySelector('x-native')
.shadowRoot.querySelector('x-component')
.shadowRoot.querySelector('div');
const token = LOWERCASE_SCOPE_TOKENS ? 'lwc-6a8uqob2ku4' : 'x-component_component';
expect(syntheticMode.hasAttribute(token)).toBe(true);
expect(nativeMode.hasAttribute(token)).toBe(false);
});
});
});
describe('static content when stylesheets change', () => {
it('should reflect correct token for scoped styles', () => {
const elm = createElement('x-container', { is: MultipleStyles });
const stylesheetsWarning =
/Mutating the "stylesheets" property on a template is deprecated and will be removed in a future version of LWC/;
expect(() => {
elm.updateTemplate({
name: 'a',
useScopedCss: false,
});
}).toLogWarningDev(stylesheetsWarning);
window.__lwcResetAlreadyLoggedMessages();
document.body.appendChild(elm);
expect(elm.shadowRoot.querySelector('div').getAttribute('class')).toBe('foo');
// atm, we need to switch templates.
expect(() => {
elm.updateTemplate({
name: 'b',
useScopedCss: true,
});
}).toLogWarningDev(stylesheetsWarning);
window.__lwcResetAlreadyLoggedMessages();
return Promise.resolve()
.then(() => {
const classList = Array.from(elm.shadowRoot.querySelector('div').classList).sort();
expect(classList).toEqual([
'foo',
LOWERCASE_SCOPE_TOKENS ? 'lwc-6fpm08fjoch' : 'x-multipleStyles_b',
]);
expect(() => {
elm.updateTemplate({
name: 'a',
useScopedCss: false,
});
}).toLogWarningDev(stylesheetsWarning);
})
.then(() => {
const classList = Array.from(elm.shadowRoot.querySelector('div').classList).sort();
expect(classList).toEqual(['foo']);
});
});
});
describe('svg and static content', () => {
it('should use correct namespace', () => {
const elm = createElement('x-svg-ns', { is: SvgNs });
document.body.appendChild(elm);
const allStaticNodes = elm.querySelectorAll('.static');
allStaticNodes.forEach((node) => {
expect(node.namespaceURI).toBe('http://www.w3.org/2000/svg');
});
});
function getDomStructure(elm) {
const tagName = elm.tagName.toLowerCase();
const result = { tagName };
for (let i = 0; i < elm.children.length; i++) {
const child = elm.children[i];
result.children = result.children || [];
result.children.push(getDomStructure(child));
}
return result;
}
it('should correctly parse <path>', () => {
const elm = createElement('x-svg-path', { is: SvgPath });
document.body.appendChild(elm);
expect(getDomStructure(elm.shadowRoot.firstChild)).toEqual({
tagName: 'svg',
children: [
{
tagName: 'path',
},
{
tagName: 'path',
},
],
});
});
it('should correctly parse <path> in div', () => {
const elm = createElement('x-svg-path-in-div', { is: SvgPathInDiv });
document.body.appendChild(elm);
expect(getDomStructure(elm.shadowRoot.firstChild)).toEqual({
tagName: 'div',
children: [
{
tagName: 'svg',
children: [
{
tagName: 'path',
},
{
tagName: 'path',
},
],
},
],
});
});
it('should correctly parse <path> in <g>', () => {
const elm = createElement('x-svg-path-in-g', { is: SvgPathInG });
document.body.appendChild(elm);
expect(getDomStructure(elm.shadowRoot.firstChild)).toEqual({
tagName: 'svg',
children: [
{
tagName: 'g',
children: [
{
tagName: 'path',
},
{
tagName: 'path',
},
],
},
],
});
});
});
describe('elements that cannot be parsed as top-level', () => {
it('should work with a static <td>', () => {
const elm = createElement('x-table', { is: Table });
document.body.appendChild(elm);
expect(elm.shadowRoot.querySelectorAll('td').length).toEqual(0);
elm.addRow();
return Promise.resolve().then(() => {
expect(elm.shadowRoot.querySelectorAll('td').length).toEqual(1);
expect(elm.shadowRoot.querySelector('td').textContent).toEqual('');
});
});
it('works for all elements that cannot be safely parsed as top-level', () => {
const elm = createElement('x-static-unsafe-top-level', { is: StaticUnsafeTopLevel });
document.body.appendChild(elm);
const getChildrenTagNames = () => {
const result = [];
const { children } = elm.shadowRoot;
for (let i = 0; i < children.length; i++) {
result.push(children[i].tagName.toLowerCase());
}
return result;
};
const expectedChildren = [
'caption',
'col',
'colgroup',
'tbody',
'td',
'tfoot',
'th',
'thead',
'tr',
];
expect(getChildrenTagNames()).toEqual([]);
elm.doRender = true;
return Promise.resolve()
.then(() => {
expect(getChildrenTagNames()).toEqual(expectedChildren);
elm.doRender = false;
})
.then(() => {
expect(getChildrenTagNames()).toEqual([]);
elm.doRender = true;
})
.then(() => {
expect(getChildrenTagNames()).toEqual(expectedChildren);
});
});
});
describe('template literal escaping', () => {
it('should properly render escaped content', () => {
const elm = createElement('x-escape', { is: Escape });
document.body.appendChild(elm);
// "`"
[
() => elm.shadowRoot.querySelector('.backtick-text').textContent,
() => elm.shadowRoot.querySelector('.backtick-comment').firstChild.textContent,
() => elm.shadowRoot.querySelector('.backtick-attr').getAttribute('data-message'),
].forEach((selector) => {
expect(selector()).toBe('Escape `me`');
});
// "\`"
[
() => elm.shadowRoot.querySelector('.backtick-escape-text').textContent,
() => elm.shadowRoot.querySelector('.backtick-escape-comment').firstChild.textContent,
() =>
elm.shadowRoot.querySelector('.backtick-escape-attr').getAttribute('data-message'),
].forEach((selector) => {
expect(selector()).toBe('Escape \\`me`');
});
// "${"
expect(elm.shadowRoot.querySelector('.dollar-attr').getAttribute('data-message')).toBe(
'Escape ${me}'
);
// "\${"
expect(
elm.shadowRoot.querySelector('.dollar-escape-attr').getAttribute('data-message')
).toBe('Escape \\${me}');
});
});
describe('static optimization with event listeners', () => {
// We test an event listener on the self, child, and grandchild, because we currently
// cannot optimize event listeners anywhere except at the top level of a static fragment.
// So we need to ensure that potentially-static parents/grandparents do not result in
// event listeners not being attached incorrectly.
const scenarios = [
{
name: 'self',
Component: OnlyEventListener,
},
{
name: 'child',
Component: OnlyEventListenerChild,
},
{
name: 'grandchild',
Component: OnlyEventListenerGrandchild,
},
];
scenarios.forEach(({ name, Component }) => {
describe(name, () => {
// CustomEvent is not supported in IE11
const CE = typeof CustomEvent === 'function' ? CustomEvent : Event;
let elm;
let button;
beforeEach(async () => {
elm = createElement('x-only-event-listener', { is: Component });
document.body.appendChild(elm);
await Promise.resolve();
button = elm.shadowRoot.querySelector('button');
});
it('works with element that is static except for event listener', async () => {
button.dispatchEvent(new CE('foo'));
button.dispatchEvent(new CE('bar'));
expect(elm.counts).toEqual({ foo: 1, bar: 1 });
// trigger re-render
elm.dynamic = 'yolo';
await Promise.resolve();
button.dispatchEvent(new CE('foo'));
button.dispatchEvent(new CE('bar'));
expect(elm.counts).toEqual({ foo: 2, bar: 2 });
});
it('can have manual listeners too', async () => {
const dispatcher = jasmine.createSpy();
button.addEventListener('baz', dispatcher);
button.dispatchEvent(new CE('baz'));
expect(dispatcher.calls.count()).toBe(1);
// trigger re-render
elm.dynamic = 'yolo';
await Promise.resolve();
button.dispatchEvent(new CE('baz'));
expect(dispatcher.calls.count()).toBe(2);
});
});
});
});
describe('event listeners on static nodes when other nodes are updated', () => {
it('event listeners work after updates', async () => {
const elm = createElement('x-listener-static-with-updates', {
is: ListenerStaticWithUpdates,
});
document.body.appendChild(elm);
await Promise.resolve();
let expectedCount = 0;
expect(elm.fooEventCount).toBe(expectedCount);
elm.fireFooEvent();
expect(elm.fooEventCount).toBe(++expectedCount);
await Promise.resolve();
for (let i = 0; i < 3; i++) {
elm.version = i;
elm.fireFooEvent();
expect(elm.fooEventCount).toBe(++expectedCount);
await Promise.resolve();
elm.fireFooEvent();
expect(elm.fooEventCount).toBe(++expectedCount);
}
});
});
describe('event listeners on deep paths', () => {
it('handles events correctly', async () => {
const elm = createElement('x-deep-listener', {
is: DeepListener,
});
document.body.appendChild(elm);
await Promise.resolve();
let count = 0;
expect(elm.counter).toBe(count);
const childElms = Object.values(extractDataIds(elm));
expect(childElms.length).toBe(12); // static1, dynamic1, deepStatic1, static2, etc. until 4
for (const childElm of childElms) {
childElm.dispatchEvent(new CustomEvent('foo'));
expect(elm.counter).toBe(++count);
}
});
});
describe('static parts applies to comments correctly', () => {
it('has correct static parts when lwc:preserve-comments is off', async () => {
const elm = createElement('x-comments', {
is: Comments,
});
document.body.appendChild(elm);
await Promise.resolve();
const { foo, bar } = extractDataIds(elm);
const refs = elm.getRefs();
foo.click();
expect(elm.fooWasClicked).toBe(true);
expect(refs.foo).toBe(foo);
bar.click();
expect(elm.barWasClicked).toBe(true);
expect(refs.bar).toBe(bar);
});
it('has correct static parts when lwc:preserve-comments is on', async () => {
const elm = createElement('x-preserve-comments', {
is: PreserveComments,
});
document.body.appendChild(elm);
await Promise.resolve();
const { foo, bar } = extractDataIds(elm);
const refs = elm.getRefs();
foo.click();
expect(elm.fooWasClicked).toBe(true);
expect(refs.foo).toBe(foo);
bar.click();
expect(elm.barWasClicked).toBe(true);
expect(refs.bar).toBe(bar);
});
});
describe('static content optimization with attribute', () => {
let nodes = {};
let elm;
beforeEach(async () => {
elm = createElement('x-attributes', { is: Attribute });
document.body.appendChild(elm);
await Promise.resolve();
nodes = extractDataIds(elm);
});
const verifyStyleAttributeAppliedCorrectly = ({ cmp, expected }) =>
expect(cmp.getAttribute('style')).toEqual(expected);
const verifyAttributeAppliedCorrectly = ({ cmp, expected }) =>
expect(cmp.getAttribute('data-value')).toEqual(expected);
const verifyClassAppliedCorrectly = ({ cmp, expected }) =>
expect(cmp.getAttribute('class')).toEqual(expected);
it('preserves static values', () => {
const {
staticAttr,
staticAttrNested,
staticClass,
staticClassBoolean,
staticClassEmpty,
staticClassNested,
staticClassSpaces,
staticClassTab,
staticClassTabs,
staticCombined,
staticCombinedNested,
staticStyle,
staticStyleBoolean,
staticStyleEmpty,
staticStyleInvalid,
staticStyleNested,
staticStyleSpaces,
staticStyleTab,
staticStyleTabs,
} = nodes;
// styles
[
{ cmp: staticStyle, expected: 'color: blue;' },
{ cmp: staticCombined, expected: 'color: red;' },
{ cmp: staticStyleNested, expected: 'color: white;' },
{ cmp: staticCombinedNested, expected: 'color: orange;' },
{ cmp: staticStyleBoolean, expected: null },
{ cmp: staticStyleEmpty, expected: null },
{ cmp: staticStyleInvalid, expected: null },
{ cmp: staticStyleSpaces, expected: null },
{ cmp: staticStyleTab, expected: null },
{ cmp: staticStyleTabs, expected: null },
].forEach(verifyStyleAttributeAppliedCorrectly);
// class
[
{ cmp: staticClass, expected: 'static class' },
{ cmp: staticCombined, expected: 'combined class' },
{ cmp: staticClassNested, expected: 'static nested class' },
{ cmp: staticCombinedNested, expected: 'static combined nested' },
{ cmp: staticClassBoolean, expected: null },
{ cmp: staticClassEmpty, expected: null },
{ cmp: staticClassSpaces, expected: null },
{ cmp: staticClassTab, expected: null },
{ cmp: staticClassTabs, expected: null },
].forEach(verifyClassAppliedCorrectly);
// attributes
[
{ cmp: staticAttr, expected: 'static1' },
{ cmp: staticCombined, expected: 'static2' },
{ cmp: staticAttrNested, expected: 'static3' },
{ cmp: staticCombinedNested, expected: 'static4' },
].forEach(verifyAttributeAppliedCorrectly);
});
it('applies expressions on mount', () => {
const {
dynamicAttr,
dynamicStyle,
dynamicClass,
dynamicAttrNested,
dynamicStyleNested,
dynamicClassNested,
dynamicCombined,
dynamicCombinedNested,
} = nodes;
// styles
[
{ cmp: dynamicStyle, expected: 'color: green;' },
{ cmp: dynamicStyleNested, expected: 'color: violet;' },
{ cmp: dynamicCombined, expected: 'color: orange;' },
{ cmp: dynamicCombinedNested, expected: 'color: black;' },
].forEach(verifyStyleAttributeAppliedCorrectly);
// class
[
{ cmp: dynamicClass, expected: 'class1' },
{ cmp: dynamicClassNested, expected: 'nestedClass1' },
{ cmp: dynamicCombined, expected: 'combinedClass' },
{ cmp: dynamicCombinedNested, expected: 'combinedClassNested' },
].forEach(verifyClassAppliedCorrectly);
// attributes
[
{ cmp: dynamicAttr, expected: 'dynamic1' },
{ cmp: dynamicAttrNested, expected: 'dynamic2' },
{ cmp: dynamicCombined, expected: 'dynamic3' },
{ cmp: dynamicCombinedNested, expected: 'dynamic4' },
].forEach(verifyAttributeAppliedCorrectly);
});
it('updates values when expressions change', async () => {
const {
dynamicAttr,
dynamicStyle,
dynamicClass,
dynamicAttrNested,
dynamicStyleNested,
dynamicClassNested,
dynamicCombined,
dynamicCombinedNested,
} = nodes;
// styles
elm.dynamicStyle = 'color: teal;';
elm.dynamicStyleNested = 'color: rose;';
elm.combinedStyle = 'color: purple;';
elm.combinedStyleNested = 'color: random;';
await Promise.resolve();
[
{ cmp: dynamicStyle, expected: 'color: teal;' },
{ cmp: dynamicStyleNested, expected: 'color: rose;' },
{ cmp: dynamicCombined, expected: 'color: purple;' },
{ cmp: dynamicCombinedNested, expected: 'color: random;' },
].forEach(verifyStyleAttributeAppliedCorrectly);
// class
elm.dynamicClass = 'class2';
elm.dynamicClassNested = 'nestedClass2';
elm.combinedClass = 'combinedClassUpdated';
elm.combinedClassNested = 'combinedClassNestedUpdated';
await Promise.resolve();
[
{ cmp: dynamicClass, expected: 'class2' },
{ cmp: dynamicClassNested, expected: 'nestedClass2' },
{ cmp: dynamicCombined, expected: 'combinedClassUpdated' },
{ cmp: dynamicCombinedNested, expected: 'combinedClassNestedUpdated' },
].forEach(verifyClassAppliedCorrectly);
// attributes
elm.dynamicAttr = 'dynamicUpdated1';
elm.dynamicAttrNested = 'dynamicUpdated2';
elm.combinedAttr = 'dynamicUpdated3';
elm.combinedAttrNested = 'dynamicUpdated4';
await Promise.resolve();
[
{ cmp: dynamicAttr, expected: 'dynamicUpdated1' },
{ cmp: dynamicAttrNested, expected: 'dynamicUpdated2' },
{ cmp: dynamicCombined, expected: 'dynamicUpdated3' },
{ cmp: dynamicCombinedNested, expected: 'dynamicUpdated4' },
].forEach(verifyAttributeAppliedCorrectly);
});
it('applies expression to deeply nested data structure', async () => {
const elm = createElement('x-deeply-nested', { is: DeepAttribute });
document.body.appendChild(elm);
await Promise.resolve();
nodes = extractDataIds(elm);
// Test includes 4 levels of depth
for (let i = 1; i < 5; i++) {
// style
[
{ cmp: nodes[`deep${i}Style`], expected: `${i}` },
{ cmp: nodes[`deep${i}StyleNested`], expected: `${i}` },
].forEach(verifyStyleAttributeAppliedCorrectly);
// class
[
{ cmp: nodes[`deep${i}Class`], expected: `${i}` },
{ cmp: nodes[`deep${i}ClassNested`], expected: `${i}` },
].forEach(verifyClassAppliedCorrectly);
// attribute
[
{ cmp: nodes[`deep${i}Attr`], expected: `${i}` },
{ cmp: nodes[`deep${i}AttrNested`], expected: `${i}` },
].forEach(verifyAttributeAppliedCorrectly);
// combined
[
{ cmp: nodes[`deep${i}Combined`], expected: `${i}` },
{ cmp: nodes[`deep${i}CombinedNested`], expected: `${i}` },
].forEach(verifyAttributeAppliedCorrectly);
}
});
});
describe('iframe onload event listener', () => {
it('works with iframe onload listener', async () => {
const elm = createElement('x-iframe-onload', { is: IframeOnload });
document.body.appendChild(elm);
// Oddly Firefox requires two macrotasks before the load event fires. Chrome/Safari only require a microtask.
await new Promise((resolve) => setTimeout(resolve));
await new Promise((resolve) => setTimeout(resolve));
expect(elm.loaded).toBeTrue();
});
});
describe('key directive', () => {
it('works with a key directive on top-level static content', async () => {
const elm = createElement('x-with-key', { is: WithKey });
document.body.appendChild(elm);
await Promise.resolve();
const tbody = elm.shadowRoot.querySelector('tbody');
expect(tbody.children.length).toBe(0);
// one child
elm.items = [0];
await Promise.resolve();
expect(tbody.children.length).toBe(1);
const trsA = [...elm.shadowRoot.querySelectorAll('tr')];
const tdsA = [...elm.shadowRoot.querySelectorAll('td')];
expect(trsA.length).toBe(1);
expect(tdsA.length).toBe(1);
// second child
elm.items = [0, 1];
await Promise.resolve();
expect(tbody.children.length).toBe(2);
const trsB = [...elm.shadowRoot.querySelectorAll('tr')];
const tdsB = [...elm.shadowRoot.querySelectorAll('td')];
expect(trsB.length).toBe(2);
expect(tdsB.length).toBe(2);
expect(trsB[0]).toBe(trsA[0]);
expect(tdsB[0]).toBe(tdsA[0]);
// switch order
elm.items = [1, 0];
await Promise.resolve();
expect(tbody.children.length).toBe(2);
const trsC = [...elm.shadowRoot.querySelectorAll('tr')];
const tdsC = [...elm.shadowRoot.querySelectorAll('td')];
expect(trsC.length).toBe(2);
expect(tdsC.length).toBe(2);
expect(trsC[0]).toBe(trsB[1]);
expect(tdsC[0]).toBe(tdsB[1]);
expect(trsC[1]).toBe(trsB[0]);
expect(tdsC[1]).toBe(tdsB[0]);
});
});
describe('static content dynamic text', () => {
it('renders expressions on mount', async () => {
const elm = createElement('x-text', { is: Text });
document.body.appendChild(elm);
await Promise.resolve();
const { emptyString, concateBeginning, concateEnd, siblings } = extractDataIds(elm);
expect(emptyString.textContent).toEqual('');
expect(concateBeginning.textContent).toEqual('default value');
expect(concateEnd.textContent).toEqual('value default');
expect(siblings.childNodes.length).toBe(2);
expect(siblings.childNodes[0].textContent).toEqual('standard text');
expect(siblings.childNodes[1].textContent).toEqual('second default');
});
it('updates expressions on mount', async () => {
const elm = createElement('x-text', { is: Text });
document.body.appendChild(elm);
await Promise.resolve();
elm.emptyString = 'not empty';
elm.dynamicText = 'updated';
elm.siblingDynamicText = 'updated second';
await Promise.resolve();
const { emptyString, concateBeginning, concateEnd, siblings } = extractDataIds(elm);
expect(emptyString.textContent).toEqual('not empty');
expect(concateBeginning.textContent).toEqual('updated value');
expect(concateEnd.textContent).toEqual('value updated');
expect(siblings.childNodes.length).toEqual(2);
expect(siblings.childNodes[0].textContent).toEqual('standard text');
expect(siblings.childNodes[1].textContent).toEqual('updated second');
});
});
describe('table with static content containing expressions', () => {
it('renders static content correctly', async () => {
const table = createElement('x-table', { is: TableWithExpression });
document.body.appendChild(table);
await Promise.resolve();
const tbody = table.shadowRoot.querySelector('tbody');
expect(tbody.children.length).toEqual(3);
const trs = [...table.shadowRoot.querySelectorAll('tr')];
const tds = [...table.shadowRoot.querySelectorAll('td')];
expect(trs.length).toEqual(3);
expect(tds.length).toEqual(3);
tds.forEach((td, i) => {
expect(td.getAttribute('class')).toEqual(`class${i}`);
expect(td.getAttribute('style')).toEqual(`color: ${i};`);
expect(td.getAttribute('data-id')).toEqual(`${i}`);
expect(td.textContent).toEqual(`value${i}`);
});
});
});
describe('text containing comments', () => {
[
{
tagName: 'x-text-without-preserve-comments',
preserveComments: false,
ctor: TextWithoutPreserveComments,
expected: {
staticText: Array(4).fill('static text'),
initialDynamicText: Array(4).fill(' text'),
updatedDynamicText: Array(4).fill('dynamic text'),
initialMixedText: ' static text<span> text</span> text ',
updatedMixedText: ' static text<span>mixed text</span>mixed text ',
},
},
{
tagName: 'x-text-with-preserve-comments',
preserveComments: true,
ctor: TextWithPreserveComments,
expected: {
staticText: [
'<!-- front -->static text',
'static<!-- middle --> text',
'static text<!-- back -->',
'<!-- front -->static<!-- middle --> text<!-- back -->',
],
initialDynamicText: [
'<!-- front --> text',
' <!-- middle -->text',
' text<!-- back -->',
'<!-- front --><!-- middle --> text<!-- back -->',
],
updatedDynamicText: [
'<!-- front -->dynamic text',
'dynamic <!-- middle -->text',
'dynamic text<!-- back -->',
'<!-- front -->dynamic<!-- middle --> text<!-- back -->',
],
initialMixedText:
'<!-- first comment --> static text<span> <!-- second comment --> text</span> text <!-- third comment-->',
updatedMixedText:
'<!-- first comment --> static text<span>mixed <!-- second comment --> text</span>mixed text <!-- third comment-->',
},
},
].forEach(({ tagName, preserveComments, ctor, expected }) => {
describe(`preserveComments ${preserveComments}`, () => {
let elm;
let nodes;
beforeEach(async () => {
elm = createElement(tagName, {
is: ctor,
});
document.body.appendChild(elm);
await Promise.resolve();
nodes = extractDataIds(elm);
});
afterAll(() => {
elm.remove();
});
const assertChildNodesInnerHTMLMatches = (actual, expected) => {
expect(actual.length).toEqual(expected.length);
// Actual is a HTMLCollection
expect(Array.from(actual).map((val) => val.innerHTML)).toEqual(expected);
};
it('renders static text correctly', () => {
const { staticText } = nodes;
assertChildNodesInnerHTMLMatches(staticText.children, expected.staticText);
});
it('renders dynamic text correctly', async () => {
const { dynamicText } = nodes;
// Initially empty variable
assertChildNodesInnerHTMLMatches(dynamicText.children, expected.initialDynamicText);
elm.dynamicText = 'dynamic';
await Promise.resolve();
assertChildNodesInnerHTMLMatches(dynamicText.children, expected.updatedDynamicText);
});
it('renders mixed static and dynamic text correctly', async () => {
const { mixedText } = nodes;
// Initially empty variable
expect(mixedText.innerHTML).toEqual(expected.initialMixedText);
elm.mixedText = 'mixed';
await Promise.resolve();
expect(mixedText.innerHTML).toEqual(expected.updatedMixedText);
});
});
});
});