Skip to content

Commit 3238fbb

Browse files
authored
test(table): add tests for MatTableDataSource (#18767)
* test(table): add tests for MatTableDataSource * switch shuffle to reverse
1 parent 239e01d commit 3238fbb

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import {MatTableDataSource} from './table-data-source';
2+
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
3+
import {MatSort, MatSortModule} from '@angular/material/sort';
4+
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
5+
import {Component, ViewChild} from '@angular/core';
6+
7+
describe('MatTableDataSource', () => {
8+
const dataSource = new MatTableDataSource();
9+
10+
beforeEach(async(() => {
11+
TestBed.configureTestingModule({
12+
imports: [MatSortModule, NoopAnimationsModule],
13+
declarations: [MatSortApp],
14+
}).compileComponents();
15+
}));
16+
17+
describe('sort', () => {
18+
let fixture: ComponentFixture<MatSortApp>;
19+
let sort: MatSort;
20+
21+
beforeEach(() => {
22+
fixture = TestBed.createComponent(MatSortApp);
23+
sort = fixture.componentInstance.sort;
24+
fixture.detectChanges();
25+
});
26+
27+
/** Test the data source's `sortData` function. */
28+
function testSortWithValues(values: any[]) {
29+
// The data source and MatSort expect the list to contain objects with values, where
30+
// the sort should be performed over a particular key.
31+
// Map the values into an array of objects where where each value is keyed by "prop"
32+
// e.g. [0, 1, 2] -> [{prop: 0}, {prop: 1}, {prop: 2}]
33+
const data = values.map(v => ({'prop': v}));
34+
35+
// Set the active sort to be on the "prop" key
36+
sort.active = 'prop';
37+
38+
const reversedData = data.slice().reverse();
39+
const sortedData = dataSource.sortData(reversedData, sort);
40+
expect(sortedData).toEqual(data);
41+
}
42+
43+
it('should be able to correctly sort an array of numbers', () => {
44+
testSortWithValues([-2, -1, 0, 1, 2]);
45+
});
46+
47+
it('should be able to correctly sort an array of string', () => {
48+
testSortWithValues(['apples', 'bananas', 'cherries', 'lemons', 'strawberries']);
49+
});
50+
});
51+
});
52+
53+
@Component({
54+
template: `<div matSort matSortDirection="asc"></div>`
55+
})
56+
class MatSortApp {
57+
@ViewChild(MatSort, {static: true}) sort: MatSort;
58+
}

0 commit comments

Comments
 (0)