File size: 1,220 Bytes
d9494a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { upsertIntoArrayOfObjectsComparingId } from '@/utils/array/upsertIntoArrayOfObjectsComparingId';

type TestObject = {
  id: string;
  name: string;
};

const mockTestObjects: TestObject[] = [
  {
    id: '1',
    name: 'Test 1',
  },
  {
    id: '2',
    name: 'Test 2',
  },
  {
    id: '3',
    name: 'Test 3',
  },
  {
    id: '4',
    name: 'Test 4',
  },
];

describe('upsertIntoArrayOfObjectsComparingId', () => {
  it('should insert in empty array', () => {
    expect(
      upsertIntoArrayOfObjectsComparingId([], mockTestObjects[0]),
    ).toStrictEqual([mockTestObjects[0]]);
  });

  it('should insert in array', () => {
    const newItem: TestObject = {
      id: '5',
      name: 'Test 5',
    };

    expect(
      upsertIntoArrayOfObjectsComparingId(mockTestObjects, newItem),
    ).toStrictEqual([...mockTestObjects, newItem]);
  });

  it('should replace in array', () => {
    const itemToReplace: TestObject = {
      id: '4',
      name: 'Test 4 replaced',
    };

    expect(
      upsertIntoArrayOfObjectsComparingId(mockTestObjects, itemToReplace),
    ).toStrictEqual([
      mockTestObjects[0],
      mockTestObjects[1],
      mockTestObjects[2],
      itemToReplace,
    ]);
  });
});