Skip to content

Commit 1f3a0f5

Browse files
committed
test(table): add tests for MatTableDataSource
1 parent 598db09 commit 1f3a0f5

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
/** Randomly shuffles the array of data. */
22+
function shuffle(data: any[]) {
23+
return data.slice().sort(() => (Math.random() - 0.5));
24+
}
25+
26+
beforeEach(() => {
27+
fixture = TestBed.createComponent(MatSortApp);
28+
sort = fixture.componentInstance.sort;
29+
fixture.detectChanges();
30+
});
31+
32+
/** Test the data source's `sortData` function. */
33+
function testSortWithValues(values: any[]) {
34+
// The data source and MatSort expect the list to contain objects with values, where
35+
// the sort should be performed over a particular key.
36+
// Map the values into an array of objects where where each value is keyed by "prop"
37+
// e.g. [0, 1, 2] -> [{prop: 0}, {prop: 1}, {prop: 2}]
38+
const data = values.map(v => ({'prop': v}));
39+
40+
// Set the active sort to be on the "prop" key
41+
sort.active = 'prop';
42+
43+
const shuffledData = shuffle(data.slice());
44+
const sortedData = dataSource.sortData(shuffledData, sort);
45+
expect(sortedData).toEqual(data);
46+
}
47+
48+
it('should be able to correctly sort an array of numbers', () => {
49+
testSortWithValues([-2, -1, 0, 1, 2]);
50+
});
51+
52+
it('should be able to correctly sort an array of string', () => {
53+
testSortWithValues(['apples', 'bananas', 'cherries', 'lemons', 'strawberries']);
54+
});
55+
});
56+
});
57+
58+
@Component({
59+
template: `<div matSort matSortDirection="asc"></div>`
60+
})
61+
class MatSortApp {
62+
@ViewChild(MatSort, {static: true}) sort: MatSort;
63+
}

0 commit comments

Comments
 (0)