/
table.spec.ts
2512 lines (2107 loc) · 91.2 KB
/
table.spec.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
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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {CollectionViewer, DataSource} from '@angular/cdk/collections';
import {
AfterContentInit,
Component,
ContentChild,
ContentChildren,
Input,
QueryList,
Type,
ViewChild,
AfterViewInit
} from '@angular/core';
import {ComponentFixture, fakeAsync, flush, TestBed} from '@angular/core/testing';
import {BehaviorSubject, combineLatest, Observable, of as observableOf} from 'rxjs';
import {map} from 'rxjs/operators';
import {CdkColumnDef} from './cell';
import {CdkTableModule} from './index';
import {CdkHeaderRowDef, CdkRowDef, CdkCellOutlet} from './row';
import {CdkTable} from './table';
import {
getTableDuplicateColumnNameError,
getTableMissingMatchingRowDefError,
getTableMissingRowDefsError,
getTableMultipleDefaultRowDefsError,
getTableUnknownColumnError,
getTableUnknownDataSourceError
} from './table-errors';
import {BidiModule} from '@angular/cdk/bidi';
describe('CdkTable', () => {
let fixture: ComponentFixture<any>;
let component: any;
let tableElement: HTMLElement;
function createComponent<T>(
componentType: Type<T>, declarations: any[] = []): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [CdkTableModule, BidiModule],
declarations: [componentType, ...declarations],
}).compileComponents();
return TestBed.createComponent<T>(componentType);
}
function setupTableTestApp(componentType: Type<any>, declarations: any[] = []) {
fixture = createComponent(componentType, declarations);
component = fixture.componentInstance;
fixture.detectChanges();
tableElement = fixture.nativeElement.querySelector('.cdk-table');
}
describe('in a typical simple use case', () => {
let dataSource: FakeDataSource;
let table: CdkTable<TestData>;
beforeEach(() => {
setupTableTestApp(SimpleCdkTableApp);
component = fixture.componentInstance as SimpleCdkTableApp;
dataSource = component.dataSource;
table = component.table;
fixture.detectChanges();
});
describe('should initialize', () => {
it('with a connected data source', () => {
expect(table.dataSource).toBe(dataSource);
expect(dataSource.isConnected).toBe(true);
});
it('with a rendered header with the right number of header cells', () => {
const header = getHeaderRows(tableElement)[0];
expect(header).toBeTruthy();
expect(header.classList).toContain('customHeaderRowClass');
expect(getHeaderCells(header).length).toBe(component.columnsToRender.length);
});
it('with rendered rows with right number of row cells', () => {
const rows = getRows(tableElement);
expect(rows.length).toBe(dataSource.data.length);
rows.forEach(row => {
expect(row.classList).toContain('customRowClass');
expect(getCells(row).length).toBe(component.columnsToRender.length);
});
});
it('with column class names provided to header and data row cells', () => {
const header = getHeaderRows(tableElement)[0];
getHeaderCells(header).forEach((headerCell, index) => {
expect(headerCell.classList).toContain(`cdk-column-${component.columnsToRender[index]}`);
});
getRows(tableElement).forEach(row => {
getCells(row).forEach((cell, index) => {
expect(cell.classList).toContain(`cdk-column-${component.columnsToRender[index]}`);
});
});
});
it('with the right accessibility roles', () => {
expect(tableElement.getAttribute('role')).toBe('grid');
expect(getHeaderRows(tableElement)[0].getAttribute('role')).toBe('row');
const header = getHeaderRows(tableElement)[0];
getHeaderCells(header).forEach(cell => {
expect(cell.getAttribute('role')).toBe('columnheader');
});
getRows(tableElement).forEach(row => {
expect(row.getAttribute('role')).toBe('row');
getCells(row).forEach(cell => {
expect(cell.getAttribute('role')).toBe('gridcell');
});
});
});
});
it('should disconnect the data source when table is destroyed', () => {
expect(dataSource.isConnected).toBe(true);
fixture.destroy();
expect(dataSource.isConnected).toBe(false);
});
it('should re-render the rows when the data changes', () => {
dataSource.addData();
fixture.detectChanges();
expect(getRows(tableElement).length).toBe(dataSource.data.length);
// Check that the number of cells is correct
getRows(tableElement).forEach(row => {
expect(getCells(row).length).toBe(component.columnsToRender.length);
});
});
it('should clear the `mostRecentCellOutlet` on destroy', () => {
// Note: we cast the assertions here to booleans, because they may
// contain circular objects which will throw Jasmine into an infinite
// when its tries to stringify them to show a test failure.
expect(!!CdkCellOutlet.mostRecentCellOutlet).toBe(true);
fixture.destroy();
expect(!!CdkCellOutlet.mostRecentCellOutlet).toBe(false);
});
describe('should correctly use the differ to add/remove/move rows', () => {
function addInitialIndexAttribute() {
// Each row receives an attribute 'initialIndex' the element's original place
getRows(tableElement).forEach((row: Element, index: number) => {
row.setAttribute('initialIndex', index.toString());
});
// Prove that the attributes match their indicies
const initialRows = getRows(tableElement);
expect(initialRows[0].getAttribute('initialIndex')).toBe('0');
expect(initialRows[1].getAttribute('initialIndex')).toBe('1');
expect(initialRows[2].getAttribute('initialIndex')).toBe('2');
}
it('when the data is heterogeneous', () => {
addInitialIndexAttribute();
// Swap first and second data in data array
const copiedData = component.dataSource!.data.slice();
const temp = copiedData[0];
copiedData[0] = copiedData[1];
copiedData[1] = temp;
// Remove the third element
copiedData.splice(2, 1);
// Add new data
component.dataSource!.data = copiedData;
component.dataSource!.addData();
// Expect that the first and second rows were swapped and that the last row is new
const changedRows = getRows(tableElement);
expect(changedRows.length).toBe(3);
expect(changedRows[0].getAttribute('initialIndex')).toBe('1');
expect(changedRows[1].getAttribute('initialIndex')).toBe('0');
expect(changedRows[2].getAttribute('initialIndex')).toBe(null);
});
it('when the data contains multiple occurrences of the same object instance', () => {
const obj = {value: true};
component.dataSource!.data = [obj, obj, obj];
addInitialIndexAttribute();
const copiedData = component.dataSource!.data.slice();
// Remove the third element and add a new different obj in the beginning.
copiedData.splice(2, 1);
copiedData.unshift({value: false});
// Add new data
component.dataSource!.data = copiedData;
// Expect that two of the three rows still have an initial index. Not as concerned about
// the order they are in, but more important that there was no unnecessary removes/inserts.
const changedRows = getRows(tableElement);
expect(changedRows.length).toBe(3);
let numInitialRows = 0;
changedRows.forEach(row => {
if (row.getAttribute('initialIndex') !== null) {
numInitialRows++;
}
});
expect(numInitialRows).toBe(2);
});
});
it('should clear the row view containers on destroy', () => {
const rowOutlet = fixture.componentInstance.table._rowOutlet.viewContainer;
const headerPlaceholder = fixture.componentInstance.table._headerRowOutlet.viewContainer;
spyOn(rowOutlet, 'clear').and.callThrough();
spyOn(headerPlaceholder, 'clear').and.callThrough();
fixture.destroy();
expect(rowOutlet.clear).toHaveBeenCalled();
expect(headerPlaceholder.clear).toHaveBeenCalled();
});
it('should match the right table content with dynamic data', () => {
const initialDataLength = dataSource.data.length;
expect(dataSource.data.length).toBe(3);
let data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
[data[1].a, data[1].b, data[1].c],
[data[2].a, data[2].b, data[2].c],
['Footer A', 'Footer B', 'Footer C'],
]);
// Add data to the table and recreate what the rendered output should be.
dataSource.addData();
expect(dataSource.data.length).toBe(initialDataLength + 1); // Make sure data was added
fixture.detectChanges();
data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
[data[1].a, data[1].b, data[1].c],
[data[2].a, data[2].b, data[2].c],
[data[3].a, data[3].b, data[3].c],
['Footer A', 'Footer B', 'Footer C'],
]);
});
it('should be able to dynamically change the columns for header and rows', () => {
expect(dataSource.data.length).toBe(3);
let data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
[data[1].a, data[1].b, data[1].c],
[data[2].a, data[2].b, data[2].c],
['Footer A', 'Footer B', 'Footer C'],
]);
// Remove column_a and swap column_b/column_c.
component.columnsToRender = ['column_c', 'column_b'];
fixture.detectChanges();
let changedTableContent = [['Column C', 'Column B']];
dataSource.data.forEach(rowData => changedTableContent.push([rowData.c, rowData.b]));
data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column C', 'Column B'],
[data[0].c, data[0].b],
[data[1].c, data[1].b],
[data[2].c, data[2].b],
['Footer C', 'Footer B'],
]);
});
});
it('should render no rows when the data is null', fakeAsync(() => {
setupTableTestApp(NullDataCdkTableApp);
fixture.detectChanges();
expect(getRows(tableElement).length).toBe(0);
}));
it('should be able to render multiple header and footer rows', () => {
setupTableTestApp(MultipleHeaderFooterRowsCdkTableApp);
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
['first-header'],
['second-header'],
['first-footer'],
['second-footer'],
]);
});
it('should be able to project a caption', fakeAsync(() => {
setupTableTestApp(NativeHtmlTableWithCaptionApp);
fixture.detectChanges();
const caption = tableElement.querySelector('caption');
expect(caption).toBeTruthy();
expect(tableElement.firstElementChild).toBe(caption);
}));
describe('with different data inputs other than data source', () => {
let baseData: TestData[] = [
{a: 'a_1', b: 'b_1', c: 'c_1'},
{a: 'a_2', b: 'b_2', c: 'c_2'},
{a: 'a_3', b: 'b_3', c: 'c_3'},
];
beforeEach(() => {
setupTableTestApp(CdkTableWithDifferentDataInputsApp);
});
it('should render with data array input', () => {
const data = baseData.slice();
component.dataSource = data;
fixture.detectChanges();
const expectedRender = [
['Column A', 'Column B', 'Column C'],
['a_1', 'b_1', 'c_1'],
['a_2', 'b_2', 'c_2'],
['a_3', 'b_3', 'c_3'],
];
expectTableToMatchContent(tableElement, expectedRender);
// Push data to the array but neglect to tell the table, should be no change
data.push({a: 'a_4', b: 'b_4', c: 'c_4'});
expectTableToMatchContent(tableElement, expectedRender);
// Notify table of the change, expect another row
component.table.renderRows();
fixture.detectChanges();
expectedRender.push(['a_4', 'b_4', 'c_4']);
expectTableToMatchContent(tableElement, expectedRender);
// Remove a row and expect the change in rows
data.pop();
component.table.renderRows();
expectedRender.pop();
expectTableToMatchContent(tableElement, expectedRender);
// Remove the data input entirely and expect no rows - just header.
component.dataSource = null;
fixture.detectChanges();
expectTableToMatchContent(tableElement, [expectedRender[0]]);
// Add back the data to verify that it renders rows
component.dataSource = data;
fixture.detectChanges();
expectTableToMatchContent(tableElement, expectedRender);
});
it('should render with data stream input', () => {
const data = baseData.slice();
const stream = new BehaviorSubject<TestData[]>(data);
component.dataSource = stream;
fixture.detectChanges();
const expectedRender = [
['Column A', 'Column B', 'Column C'],
['a_1', 'b_1', 'c_1'],
['a_2', 'b_2', 'c_2'],
['a_3', 'b_3', 'c_3'],
];
expectTableToMatchContent(tableElement, expectedRender);
// Push data to the array and emit the data array on the stream
data.push({a: 'a_4', b: 'b_4', c: 'c_4'});
stream.next(data);
fixture.detectChanges();
expectedRender.push(['a_4', 'b_4', 'c_4']);
expectTableToMatchContent(tableElement, expectedRender);
// Push data to the array but rather than emitting, call renderRows.
data.push({a: 'a_5', b: 'b_5', c: 'c_5'});
component.table.renderRows();
fixture.detectChanges();
expectedRender.push(['a_5', 'b_5', 'c_5']);
expectTableToMatchContent(tableElement, expectedRender);
// Remove a row and expect the change in rows
data.pop();
expectedRender.pop();
stream.next(data);
expectTableToMatchContent(tableElement, expectedRender);
// Remove the data input entirely and expect no rows - just header.
component.dataSource = null;
fixture.detectChanges();
expectTableToMatchContent(tableElement, [expectedRender[0]]);
// Add back the data to verify that it renders rows
component.dataSource = stream;
fixture.detectChanges();
expectTableToMatchContent(tableElement, expectedRender);
});
it('should throw an error if the data source is not valid', () => {
component.dataSource = {invalid: 'dataSource'};
expect(() => fixture.detectChanges()).toThrowError(getTableUnknownDataSourceError().message);
});
it('should throw an error if the data source is not valid', () => {
component.dataSource = undefined;
fixture.detectChanges();
// Expect the table to render just the header, no rows
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C']
]);
});
});
describe('missing row defs', () => {
it('should be able to render without a header row def', () => {
setupTableTestApp(MissingHeaderRowDefCdkTableApp);
expectTableToMatchContent(tableElement, [
['a_1'], // Data rows
['a_2'],
['a_3'],
['Footer A'], // Footer row
]);
});
it('should be able to render without a data row def', () => {
setupTableTestApp(MissingRowDefCdkTableApp);
expectTableToMatchContent(tableElement, [
['Column A'], // Header row
['Footer A'], // Footer row
]);
});
it('should be able to render without a footer row def', () => {
setupTableTestApp(MissingFooterRowDefCdkTableApp);
expectTableToMatchContent(tableElement, [
['Column A'], // Header row
['a_1'], // Data rows
['a_2'],
['a_3'],
]);
});
});
it('should render correctly when using native HTML tags', () => {
const thisFixture = createComponent(NativeHtmlTableApp);
const thisTableElement = thisFixture.nativeElement.querySelector('table');
thisFixture.detectChanges();
expectTableToMatchContent(thisTableElement, [
['Column A', 'Column B', 'Column C'],
['a_1', 'b_1', 'c_1'],
['a_2', 'b_2', 'c_2'],
['a_3', 'b_3', 'c_3'],
]);
});
it('should be able to nest tables', () => {
const thisFixture = createComponent(NestedHtmlTableApp);
thisFixture.detectChanges();
const outerTable = thisFixture.nativeElement.querySelector('table');
const innerTable = outerTable.querySelector('table');
const outerRows = Array.from<HTMLTableRowElement>(outerTable.querySelector('tbody').rows);
const innerRows = Array.from<HTMLTableRowElement>(innerTable.querySelector('tbody').rows);
expect(outerTable).toBeTruthy();
expect(outerRows.map(row => row.cells.length)).toEqual([3, 3, 3]);
expect(innerTable).toBeTruthy();
expect(innerRows.map(row => row.cells.length)).toEqual([3, 3, 3]);
});
it('should apply correct roles for native table elements', () => {
const thisFixture = createComponent(NativeHtmlTableApp);
const thisTableElement: HTMLTableElement = thisFixture.nativeElement.querySelector('table');
thisFixture.detectChanges();
const rowGroups = Array.from(thisTableElement.querySelectorAll('thead, tbody, tfoot'));
expect(rowGroups.length).toBe(3, 'Expected table to have a thead, tbody, and tfoot');
for (const group of rowGroups) {
expect(group.getAttribute('role'))
.toBe('rowgroup', 'Expected thead, tbody, and tfoot to have role="rowgroup"');
}
});
it('should hide thead/tfoot when there are no header/footer rows', () => {
const thisFixture = createComponent(NativeTableWithNoHeaderOrFooterRows);
const thisTableElement: HTMLTableElement = thisFixture.nativeElement.querySelector('table');
thisFixture.detectChanges();
const rowGroups: HTMLElement[] = Array.from(thisTableElement.querySelectorAll('thead, tfoot'));
expect(rowGroups.length).toBe(2, 'Expected table to have a thead and tfoot');
for (const group of rowGroups) {
expect(group.style.display).toBe('none', 'Expected thead and tfoot to be `display: none`');
}
});
it('should render cells even if row data is falsy', () => {
setupTableTestApp(BooleanRowCdkTableApp);
expectTableToMatchContent(tableElement, [
[''], // Header row
['false'], // Data rows
['true'],
['false'],
['true'],
]);
});
it('should be able to apply class-friendly css class names for the column cells', () => {
setupTableTestApp(CrazyColumnNameCdkTableApp);
// Column was named 'crazy-column-NAME-1!@#$%^-_&*()2'
const header = getHeaderRows(tableElement)[0];
expect(getHeaderCells(header)[0].classList)
.toContain('cdk-column-crazy-column-NAME-1-------_----2');
});
it('should not clobber an existing table role', () => {
setupTableTestApp(CustomRoleCdkTableApp);
expect(tableElement.getAttribute('role')).toBe('treegrid');
});
it('should throw an error if two column definitions have the same name', () => {
expect(() => createComponent(DuplicateColumnDefNameCdkTableApp).detectChanges())
.toThrowError(getTableDuplicateColumnNameError('column_a').message);
});
it('should throw an error if a column definition is requested but not defined', () => {
expect(() => createComponent(MissingColumnDefCdkTableApp).detectChanges())
.toThrowError(getTableUnknownColumnError('column_a').message);
});
it('should pick up columns that are indirect descendants', () => {
expect(() => createComponent(TableWithIndirectDescendantDefs).detectChanges()).not.toThrow();
});
it('should throw an error if a column definition is requested but not defined after render',
fakeAsync(() => {
const columnDefinitionMissingAfterRenderFixture =
createComponent(MissingColumnDefAfterRenderCdkTableApp);
expect(() => {
columnDefinitionMissingAfterRenderFixture.detectChanges();
flush();
columnDefinitionMissingAfterRenderFixture.detectChanges();
}).toThrowError(getTableUnknownColumnError('column_a').message);
}));
it('should throw an error if the row definitions are missing', () => {
expect(() => createComponent(MissingAllRowDefsCdkTableApp).detectChanges())
.toThrowError(getTableMissingRowDefsError().message);
});
it('should not throw an error if columns are undefined on initialization', () => {
setupTableTestApp(UndefinedColumnsCdkTableApp);
// Header should be empty since there are no columns to display.
const headerRow = getHeaderRows(tableElement)[0];
expect(headerRow.textContent).toBe('');
// Rows should be empty since there are no columns to display.
const rows = getRows(tableElement);
expect(rows[0].textContent).toBe('');
expect(rows[1].textContent).toBe('');
expect(rows[2].textContent).toBe('');
});
it('should be able to dynamically add/remove column definitions', () => {
setupTableTestApp(DynamicColumnDefinitionsCdkTableApp);
// Add a new column and expect it to show up in the table
let columnA = 'columnA';
component.dynamicColumns.push(columnA);
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
[columnA], // Header row
[columnA], // Data rows
[columnA],
[columnA],
]);
// Add another new column and expect it to show up in the table
let columnB = 'columnB';
component.dynamicColumns.push(columnB);
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
[columnA, columnB], // Header row
[columnA, columnB], // Data rows
[columnA, columnB],
[columnA, columnB],
]);
// Remove column A expect only column B to be rendered
component.dynamicColumns.shift();
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
[columnB], // Header row
[columnB], // Data rows
[columnB],
[columnB],
]);
});
it('should be able to register column, row, and header row definitions outside content', () => {
setupTableTestApp(OuterTableApp, [WrapperCdkTableApp]);
// The first two columns were defined in the wrapped table component as content children,
// while the injected columns were provided to the wrapped table from the outer component.
// A special row was provided with a when predicate that shows the single column with text.
// The header row was defined by the outer component.
expectTableToMatchContent(tableElement, [
['Content Column A', 'Content Column B', 'Injected Column A', 'Injected Column B'],
['injected row with when predicate'],
['a_2', 'b_2', 'a_2', 'b_2'],
['a_3', 'b_3', 'a_3', 'b_3']
]);
});
describe('using when predicate', () => {
it('should be able to display different row templates based on the row data', () => {
setupTableTestApp(WhenRowCdkTableApp);
let data = component.dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
['index_1_special_row'],
['c3_special_row'],
[data[3].a, data[3].b, data[3].c],
]);
});
it('should error if there is row data that does not have a matching row template',
fakeAsync(() => {
const whenRowWithoutDefaultFixture = createComponent(WhenRowWithoutDefaultCdkTableApp);
const data = whenRowWithoutDefaultFixture.componentInstance.dataSource.data;
expect(() => {
try {
whenRowWithoutDefaultFixture.detectChanges();
flush();
} catch {
flush();
}
}).toThrowError(getTableMissingMatchingRowDefError(data[0]).message);
}));
it('should fail when multiple rows match data without multiTemplateDataRows', fakeAsync(() => {
let whenFixture = createComponent(WhenRowMultipleDefaultsCdkTableApp);
expect(() => {
whenFixture.detectChanges();
flush();
}).toThrowError(getTableMultipleDefaultRowDefsError().message);
}));
describe('with multiTemplateDataRows', () => {
it('should be able to render multiple rows per data object', () => {
setupTableTestApp(WhenRowCdkTableApp);
component.multiTemplateDataRows = true;
fixture.detectChanges();
const data = component.dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
[data[1].a, data[1].b, data[1].c],
['index_1_special_row'],
[data[2].a, data[2].b, data[2].c],
['c3_special_row'],
[data[3].a, data[3].b, data[3].c],
]);
});
it('should have the correct data and row indicies', () => {
setupTableTestApp(WhenRowCdkTableApp);
component.multiTemplateDataRows = true;
component.showIndexColumns();
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
['Index', 'Data Index', 'Render Index'],
['', '0', '0'],
['', '1', '1'],
['', '1', '2'],
['', '2', '3'],
['', '2', '4'],
['', '3', '5'],
]);
});
it('should have the correct data and row indicies when data contains multiple instances of ' +
'the same object instance',
() => {
setupTableTestApp(WhenRowCdkTableApp);
component.multiTemplateDataRows = true;
component.showIndexColumns();
const obj = {value: true};
component.dataSource.data = [obj, obj, obj, obj];
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
['Index', 'Data Index', 'Render Index'],
['', '0', '0'],
['', '1', '1'],
['', '1', '2'],
['', '2', '3'],
['', '3', '4'],
]);
// Push unique data on the front and add another obj to the array
component.dataSource.data = [{value: false}, obj, obj, obj, obj, obj];
fixture.detectChanges();
expectTableToMatchContent(tableElement, [
['Index', 'Data Index', 'Render Index'],
['', '0', '0'],
['', '1', '1'],
['', '1', '2'],
['', '2', '3'],
['', '3', '4'],
['', '4', '5'],
['', '5', '6'],
]);
});
it('should not throw when multiTemplateDataRows is coerced from a static value', () => {
expect(() => {
setupTableTestApp(CoercedMultiTemplateDataRows);
fixture.detectChanges();
}).not.toThrow();
});
});
});
describe('with sticky positioning', () => {
interface PositionDirections {
[key: string]: string | undefined;
top?: string;
bottom?: string;
left?: string;
right?: string;
}
function expectNoStickyStyles(elements: any[]) {
elements.forEach(element => {
expect(element.classList.contains('cdk-table-sticky')).toBe(false);
expect(element.style.position).toBe('');
expect(element.style.zIndex || '0').toBe('0');
['top', 'bottom', 'left', 'right'].forEach(d => {
expect(element.style[d] || 'unset').toBe('unset', `Expected ${d} to be unset`);
});
});
}
function expectStickyStyles(element: any, zIndex: string, directions: PositionDirections = {}) {
expect(element.style.position).toContain('sticky');
expect(element.style.zIndex).toBe(zIndex, `Expected zIndex to be ${zIndex}`);
['top', 'bottom', 'left', 'right'].forEach(d => {
const directionValue = directions[d];
if (!directionValue) {
// If no expected position for this direction, must either be unset or empty string
expect(element.style[d] || 'unset').toBe('unset', `Expected ${d} to be unset`);
return;
}
const expectationMessage = `Expected direction ${d} to be ${directionValue}`;
// If the direction contains `px`, we parse the number to be able to avoid deviations
// caused by individual browsers.
if (directionValue.includes('px')) {
expect(Math.round(parseInt(element.style[d])))
.toBe(Math.round(parseInt(directionValue)), expectationMessage);
} else {
expect(element.style[d]).toBe(directionValue, expectationMessage);
}
});
}
describe('on "display: flex" table style', () => {
let dataRows: Element[];
let headerRows: Element[];
let footerRows: Element[];
beforeEach(() => {
setupTableTestApp(StickyFlexLayoutCdkTableApp);
headerRows = getHeaderRows(tableElement);
footerRows = getFooterRows(tableElement);
dataRows = getRows(tableElement);
});
it('should stick and unstick headers', () => {
component.stickyHeaders = ['header-1', 'header-3'];
fixture.detectChanges();
expectStickyStyles(headerRows[0], '100', {top: '0px'});
expectNoStickyStyles([headerRows[1]]);
expectStickyStyles(
headerRows[2], '100', {top: headerRows[0].getBoundingClientRect().height + 'px'});
component.stickyHeaders = [];
fixture.detectChanges();
expectNoStickyStyles(headerRows);
});
it('should stick and unstick footers', () => {
component.stickyFooters = ['footer-1', 'footer-3'];
fixture.detectChanges();
expectStickyStyles(
footerRows[0], '10', {bottom: footerRows[1].getBoundingClientRect().height + 'px'});
expectNoStickyStyles([footerRows[1]]);
expectStickyStyles(footerRows[2], '10', {bottom: '0px'});
component.stickyFooters = [];
fixture.detectChanges();
expectNoStickyStyles(footerRows);
});
it('should stick and unstick left columns', () => {
component.stickyStartColumns = ['column-1', 'column-3'];
fixture.detectChanges();
headerRows.forEach(row => {
let cells = getHeaderCells(row);
expectStickyStyles(cells[0], '1', {left: '0px'});
expectStickyStyles(cells[2], '1', {left: '20px'});
expectNoStickyStyles([cells[1], cells[3], cells[4], cells[5]]);
});
dataRows.forEach(row => {
let cells = getCells(row);
expectStickyStyles(cells[0], '1', {left: '0px'});
expectStickyStyles(cells[2], '1', {left: '20px'});
expectNoStickyStyles([cells[1], cells[3], cells[4], cells[5]]);
});
footerRows.forEach(row => {
let cells = getFooterCells(row);
expectStickyStyles(cells[0], '1', {left: '0px'});
expectStickyStyles(cells[2], '1', {left: '20px'});
expectNoStickyStyles([cells[1], cells[3], cells[4], cells[5]]);
});
component.stickyStartColumns = [];
fixture.detectChanges();
headerRows.forEach(row => expectNoStickyStyles(getHeaderCells(row)));
dataRows.forEach(row => expectNoStickyStyles(getCells(row)));
footerRows.forEach(row => expectNoStickyStyles(getFooterCells(row)));
});
it('should stick and unstick right columns', () => {
component.stickyEndColumns = ['column-4', 'column-6'];
fixture.detectChanges();
headerRows.forEach(row => {
let cells = getHeaderCells(row);
expectStickyStyles(cells[5], '1', {right: '0px'});
expectStickyStyles(cells[3], '1', {right: '20px'});
expectNoStickyStyles([cells[0], cells[1], cells[2], cells[4]]);
});
dataRows.forEach(row => {
let cells = getCells(row);
expectStickyStyles(cells[5], '1', {right: '0px'});
expectStickyStyles(cells[3], '1', {right: '20px'});
expectNoStickyStyles([cells[0], cells[1], cells[2], cells[4]]);
});
footerRows.forEach(row => {
let cells = getFooterCells(row);
expectStickyStyles(cells[5], '1', {right: '0px'});
expectStickyStyles(cells[3], '1', {right: '20px'});
expectNoStickyStyles([cells[0], cells[1], cells[2], cells[4]]);
});
component.stickyEndColumns = [];
fixture.detectChanges();
headerRows.forEach(row => expectNoStickyStyles(getHeaderCells(row)));
dataRows.forEach(row => expectNoStickyStyles(getCells(row)));
footerRows.forEach(row => expectNoStickyStyles(getFooterCells(row)));
});
it('should reverse directions for sticky columns in rtl', () => {
component.dir = 'rtl';
component.stickyStartColumns = ['column-1', 'column-2'];
component.stickyEndColumns = ['column-5', 'column-6'];
fixture.detectChanges();
const firstColumnWidth = getHeaderCells(headerRows[0])[0].getBoundingClientRect().width;
const lastColumnWidth = getHeaderCells(headerRows[0])[5].getBoundingClientRect().width;
let headerCells = getHeaderCells(headerRows[0]);
expectStickyStyles(headerCells[0], '1', {right: '0px'});
expectStickyStyles(headerCells[1], '1', {right: `${firstColumnWidth}px`});
expectStickyStyles(headerCells[4], '1', {left: `${lastColumnWidth}px`});
expectStickyStyles(headerCells[5], '1', {left: '0px'});
dataRows.forEach(row => {
let cells = getCells(row);
expectStickyStyles(cells[0], '1', {right: '0px'});
expectStickyStyles(cells[1], '1', {right: `${firstColumnWidth}px`});
expectStickyStyles(cells[4], '1', {left: `${lastColumnWidth}px`});
expectStickyStyles(cells[5], '1', {left: '0px'});
});
let footerCells = getFooterCells(footerRows[0]);
expectStickyStyles(footerCells[0], '1', {right: '0px'});
expectStickyStyles(footerCells[1], '1', {right: `${firstColumnWidth}px`});
expectStickyStyles(footerCells[4], '1', {left: `${lastColumnWidth}px`});
expectStickyStyles(footerCells[5], '1', {left: '0px'});
});
it('should stick and unstick combination of sticky header, footer, and columns', () => {
component.stickyHeaders = ['header-1'];
component.stickyFooters = ['footer-3'];
component.stickyStartColumns = ['column-1'];
component.stickyEndColumns = ['column-6'];
fixture.detectChanges();
let headerCells = getHeaderCells(headerRows[0]);
expectStickyStyles(headerRows[0], '100', {top: '0px'});
expectStickyStyles(headerCells[0], '1', {left: '0px'});
expectStickyStyles(headerCells[5], '1', {right: '0px'});
expectNoStickyStyles([headerCells[1], headerCells[2], headerCells[3], headerCells[4]]);
expectNoStickyStyles([headerRows[1], headerRows[2]]);
dataRows.forEach(row => {
let cells = getCells(row);
expectStickyStyles(cells[0], '1', {left: '0px'});
expectStickyStyles(cells[5], '1', {right: '0px'});
expectNoStickyStyles([cells[1], cells[2], cells[3], cells[4]]);
});
let footerCells = getFooterCells(footerRows[0]);
expectStickyStyles(footerRows[0], '10', {bottom: '0px'});
expectStickyStyles(footerCells[0], '1', {left: '0px'});
expectStickyStyles(footerCells[5], '1', {right: '0px'});
expectNoStickyStyles([footerCells[1], footerCells[2], footerCells[3], footerCells[4]]);
expectNoStickyStyles([footerRows[1], footerRows[2]]);
component.stickyHeaders = [];
component.stickyFooters = [];
component.stickyStartColumns = [];
component.stickyEndColumns = [];
fixture.detectChanges();
headerRows.forEach(row => expectNoStickyStyles([row, ...getHeaderCells(row)]));
dataRows.forEach(row => expectNoStickyStyles([row, ...getCells(row)]));
footerRows.forEach(row => expectNoStickyStyles([row, ...getFooterCells(row)]));
});
});
describe('on native table layout', () => {
let dataRows: Element[];
let headerRows: Element[];
let footerRows: Element[];
beforeEach(() => {
setupTableTestApp(StickyNativeLayoutCdkTableApp);
headerRows = getHeaderRows(tableElement);
footerRows = getFooterRows(tableElement);
dataRows = getRows(tableElement);
});
it('should stick and unstick headers', () => {
component.stickyHeaders = ['header-1', 'header-3'];
fixture.detectChanges();
getHeaderCells(headerRows[0]).forEach(cell => {
expectStickyStyles(cell, '100', {top: '0px'});
});
const firstHeaderHeight = headerRows[0].getBoundingClientRect().height;
getHeaderCells(headerRows[2]).forEach(cell => {
expectStickyStyles(cell, '100', {top: firstHeaderHeight + 'px'});
});