/
test.js
63 lines (52 loc) · 1.6 KB
/
test.js
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
import test from 'ava';
import arrayToObj from '.';
test('guards against invalid input types', t => {
const err = t.throws(() => {
arrayToObj(123);
}, TypeError);
t.is(err.message, 'Expected an array, got number');
});
test('it uses the id as object keys by default', t => {
const dogs = [
{id: 'first-dog', breed: 'Retriever'},
{id: 'second-dog', breed: 'Catahoula'}
];
t.deepEqual(arrayToObj(dogs), {
'first-dog': {id: 'first-dog', breed: 'Retriever'},
'second-dog': {id: 'second-dog', breed: 'Catahoula'}
});
});
test('it accepts a string as a key selector', t => {
const options = {key: 'name'};
const dogs = [
{created: '2018-09-13T07:00:00.000Z', name: 'Alex'},
{created: '2018-09-14T09:00:00.000Z', name: 'Jesse'}
];
t.deepEqual(arrayToObj(dogs, options), {
Alex: {created: '2018-09-13T07:00:00.000Z', name: 'Alex'},
Jesse: {created: '2018-09-14T09:00:00.000Z', name: 'Jesse'}
});
});
test('it accepts a key selector function', t => {
const options = {key: dog => dog.breed.toLowerCase()};
const dogs = [
{name: 'Alex', breed: 'Retriever'},
{name: 'Fingers', breed: 'Catahoula'}
];
t.deepEqual(arrayToObj(dogs, options), {
retriever: {breed: 'Retriever', name: 'Alex'},
catahoula: {breed: 'Catahoula', name: 'Fingers'}
});
});
test('falls back to the array index as a key', t => {
const options = {key: dog => dog.fake};
const dogs = [
{breed: 'Retriever'},
{breed: 'Catahoula'}
];
const result = arrayToObj(dogs, options);
t.deepEqual(result, {
0: {breed: 'Retriever'},
1: {breed: 'Catahoula'}
});
});