2.0 KB62 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import Immutable, {List} from 'immutable';
9import {SelfUpdate} from '../immutableExt';
10
11describe('SelfUpdate', () => {
12 it('is needed because of immutable.js deepEquals', () => {
13 const list1 = nestedList(10);
14 const list2 = nestedList(10);
15 // Immutable.is performs deepEqual repetitively.
16 expect(immutableIsCallCounts(list1, list2)).toMatchObject([11, 11, 11]);
17 });
18
19 it('avoids repetitive deepEquals', () => {
20 const list1 = new SelfUpdate(nestedList(10));
21 const list2 = new SelfUpdate(nestedList(10));
22 expect(immutableIsCallCounts(list1, list2)).toMatchObject([11, 1, 1]);
23 });
24
25 it('does not equal to a different type', () => {
26 const list1 = new SelfUpdate(nestedList(10));
27 const list2 = nestedList(10);
28 expect(Immutable.is(list1, list2)).toBeFalsy();
29 expect(Immutable.is(list2, list1)).toBeFalsy();
30 expect(list2.equals(list1)).toBeFalsy();
31 expect(list1.equals(list2)).toBeFalsy();
32 });
33
34 it('helps when used as a nested item', () => {
35 const list1 = List([List([new SelfUpdate(nestedList(8))])]);
36 const list2 = List([List([new SelfUpdate(nestedList(8))])]);
37 expect(immutableIsCallCounts(list1, list2)).toMatchObject([11, 3, 3]);
38 });
39});
40
41type NestedList = List<number | NestedList>;
42
43/** Construct a nested List of a given depth. */
44function nestedList(depth: number): NestedList {
45 return depth <= 0 ? List([10]) : List([nestedList(depth - 1)]);
46}
47
48/** Call Immutable.is n times, return call counts. */
49function immutableIsCallCounts(a: unknown, b: unknown, n = 3): Array<number> {
50 const ListEqualsMock = jest.spyOn(List.prototype, 'equals');
51 const counts = Array.from({length: n}, () => {
52 if (!Immutable.is(a, b)) {
53 return -1;
54 }
55 const count = ListEqualsMock.mock.calls.length;
56 ListEqualsMock.mockClear();
57 return count;
58 });
59 ListEqualsMock.mockRestore();
60 return counts;
61}
62