addons/shared/__tests__/immutableExt.test.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import Immutable, {List} from 'immutable';
b69ab319import {SelfUpdate} from '../immutableExt';
b69ab3110
b69ab3111describe('SelfUpdate', () => {
b69ab3112 it('is needed because of immutable.js deepEquals', () => {
b69ab3113 const list1 = nestedList(10);
b69ab3114 const list2 = nestedList(10);
b69ab3115 // Immutable.is performs deepEqual repetitively.
b69ab3116 expect(immutableIsCallCounts(list1, list2)).toMatchObject([11, 11, 11]);
b69ab3117 });
b69ab3118
b69ab3119 it('avoids repetitive deepEquals', () => {
b69ab3120 const list1 = new SelfUpdate(nestedList(10));
b69ab3121 const list2 = new SelfUpdate(nestedList(10));
b69ab3122 expect(immutableIsCallCounts(list1, list2)).toMatchObject([11, 1, 1]);
b69ab3123 });
b69ab3124
b69ab3125 it('does not equal to a different type', () => {
b69ab3126 const list1 = new SelfUpdate(nestedList(10));
b69ab3127 const list2 = nestedList(10);
b69ab3128 expect(Immutable.is(list1, list2)).toBeFalsy();
b69ab3129 expect(Immutable.is(list2, list1)).toBeFalsy();
b69ab3130 expect(list2.equals(list1)).toBeFalsy();
b69ab3131 expect(list1.equals(list2)).toBeFalsy();
b69ab3132 });
b69ab3133
b69ab3134 it('helps when used as a nested item', () => {
b69ab3135 const list1 = List([List([new SelfUpdate(nestedList(8))])]);
b69ab3136 const list2 = List([List([new SelfUpdate(nestedList(8))])]);
b69ab3137 expect(immutableIsCallCounts(list1, list2)).toMatchObject([11, 3, 3]);
b69ab3138 });
b69ab3139});
b69ab3140
b69ab3141type NestedList = List<number | NestedList>;
b69ab3142
b69ab3143/** Construct a nested List of a given depth. */
b69ab3144function nestedList(depth: number): NestedList {
b69ab3145 return depth <= 0 ? List([10]) : List([nestedList(depth - 1)]);
b69ab3146}
b69ab3147
b69ab3148/** Call Immutable.is n times, return call counts. */
b69ab3149function immutableIsCallCounts(a: unknown, b: unknown, n = 3): Array<number> {
b69ab3150 const ListEqualsMock = jest.spyOn(List.prototype, 'equals');
b69ab3151 const counts = Array.from({length: n}, () => {
b69ab3152 if (!Immutable.is(a, b)) {
b69ab3153 return -1;
b69ab3154 }
b69ab3155 const count = ListEqualsMock.mock.calls.length;
b69ab3156 ListEqualsMock.mockClear();
b69ab3157 return count;
b69ab3158 });
b69ab3159 ListEqualsMock.mockRestore();
b69ab3160 return counts;
b69ab3161}