Add unit tests for sortBy

This commit is contained in:
Richard Cox 2023-09-06 15:41:56 +01:00
parent b9180782e2
commit abaa2d0adc
1 changed files with 61 additions and 0 deletions

View File

@ -0,0 +1,61 @@
import { sortBy } from '@shell/utils/sort';
describe('fx: sort', () => {
describe('sortBy', () => {
const testSortBy = <T = object[]>(ary: T[], key: string[], expected: T[], desc?: boolean) => {
const result = sortBy(ary, key, desc);
expect(result).toStrictEqual(expected);
};
it.each([
[[{ a: 1 }, { a: 9 }], ['a'], [{ a: 1 }, { a: 9 }]],
[[{ a: 2 }, { a: 1 }], ['a'], [{ a: 1 }, { a: 2 }]],
])('should sort by single property', (ary, key, expected) => {
testSortBy(ary, key, expected);
});
it.each([
[[{ a: 1, b: 1 }, { a: 9, b: 9 }], ['a', 'b'], [{ a: 1, b: 1 }, { a: 9, b: 9 }]],
[[{ a: 2, b: 2 }, { a: 1, b: 1 }], ['a', 'b'], [{ a: 1, b: 1 }, { a: 2, b: 2 }]],
[[{ a: 2, b: 1 }, { a: 1, b: 9 }], ['a', 'b'], [{ a: 1, b: 9 }, { a: 2, b: 1 }]],
[[{ a: 1, b: 2 }, { a: 9, b: 1 }], ['a', 'b'], [{ a: 1, b: 2 }, { a: 9, b: 1 }]],
[[{ a: 1, b: 1 }, { a: 9, b: 9 }], ['a', 'b'], [{ a: 1, b: 1 }, { a: 9, b: 9 }]],
])('should sort by two properties (primary property always first)', (ary, key, expected) => {
testSortBy(ary, key, expected);
});
it.each([
[[{ a: 1, b: 1 }, { a: 1, b: 9 }], ['a', 'b'], [{ a: 1, b: 1 }, { a: 1, b: 9 }]],
[[{ a: 1, b: 2 }, { a: 1, b: 1 }], ['a', 'b'], [{ a: 1, b: 1 }, { a: 1, b: 2 }]],
])('should sort by two properties (primary property the same)', (ary, key, expected) => {
testSortBy(ary, key, expected);
});
describe('descending', () => {
it.each([
[[{ a: 1 }, { a: 9 }], ['a'], [{ a: 9 }, { a: 1 }]],
[[{ a: 2 }, { a: 1 }], ['a'], [{ a: 2 }, { a: 1 }]],
])('should sort by single property', (ary, key, expected) => {
testSortBy(ary, key, expected, true);
});
it.each([
[[{ a: 1, b: 1 }, { a: 9, b: 9 }], ['a', 'b'], [{ a: 9, b: 9 }, { a: 1, b: 1 }]],
[[{ a: 2, b: 2 }, { a: 1, b: 1 }], ['a', 'b'], [{ a: 2, b: 2 }, { a: 1, b: 1 }]],
[[{ a: 2, b: 1 }, { a: 1, b: 9 }], ['a', 'b'], [{ a: 2, b: 1 }, { a: 1, b: 9 }]],
[[{ a: 1, b: 2 }, { a: 9, b: 1 }], ['a', 'b'], [{ a: 9, b: 1 }, { a: 1, b: 2 }]],
[[{ a: 1, b: 1 }, { a: 9, b: 9 }], ['a', 'b'], [{ a: 9, b: 9 }, { a: 1, b: 1 }]],
])('should sort by two properties', (ary, key, expected) => {
testSortBy(ary, key, expected, true);
});
it.each([
[[{ a: 1, b: 1 }, { a: 1, b: 9 }], ['a', 'b'], [{ a: 1, b: 9 }, { a: 1, b: 1 }]],
[[{ a: 1, b: 2 }, { a: 1, b: 1 }], ['a', 'b'], [{ a: 1, b: 2 }, { a: 1, b: 1 }]],
])('should sort by two properties (primary property the same)', (ary, key, expected) => {
testSortBy(ary, key, expected, true);
});
});
});
});