useStructuralSharing.spec.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import {structuralSharing} from '../utils/useStructuralSharing';
  2. describe('structuralSharing', () => {
  3. it('should return the same object if nothing changed', () => {
  4. const obj = {a: 1, b: 2};
  5. expect(structuralSharing(obj, {...obj})).toBe(obj);
  6. });
  7. it('should return a new object if something changed', () => {
  8. const obj = {a: 1, b: 2};
  9. expect(structuralSharing(obj, {...obj, a: 2})).not.toBe(obj);
  10. expect(structuralSharing(obj, {...obj, a: 2})).toEqual({a: 2, b: 2});
  11. });
  12. it('should return the same array if nothing changed', () => {
  13. const arr = [1, 2, 3];
  14. expect(structuralSharing(arr, [...[1, 2, 3]])).toBe(arr);
  15. });
  16. it('should remove array elements', () => {
  17. const arr = [1, 2, 3];
  18. expect(structuralSharing(arr, [1, 2])).not.toBe(arr);
  19. expect(structuralSharing(arr, [1, 2])).toEqual([1, 2]);
  20. });
  21. it('should return a new array if something changed', () => {
  22. const arr = [1, 2, 3];
  23. expect(structuralSharing(arr, [...[1, 2, 4]])).not.toBe(arr);
  24. expect(structuralSharing(arr, [...[1, 2, 4]])).toEqual([1, 2, 4]);
  25. });
  26. it('should handle changes in nested objects', () => {
  27. const obj = {a: {b: 1}, c: {d: 2}};
  28. const newObj = structuralSharing(obj, {...obj, a: {b: 2}});
  29. expect(newObj).toEqual({a: {b: 2}, c: {d: 2}});
  30. expect(newObj).not.toBe(obj);
  31. expect(newObj.a).not.toBe(obj.a);
  32. expect(newObj.a.b).toBe(2);
  33. expect(newObj.c).toBe(obj.c);
  34. });
  35. it('should handle changes in nested arrays', () => {
  36. const arr = [{a: 1}, {b: 2}];
  37. const newArr = structuralSharing(arr, [arr[0], {b: 3}, {c: 4}]);
  38. expect(newArr).toEqual([{a: 1}, {b: 3}, {c: 4}]);
  39. expect(newArr).not.toBe(arr);
  40. expect(newArr[0]).toBe(arr[0]);
  41. expect(newArr[1]).not.toBe(arr[1]);
  42. expect(newArr[2]).not.toBe(arr[2]);
  43. });
  44. });