diff.test.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { describe, expect, it } from 'vitest';
  2. import { diff } from './diff';
  3. describe('diff function', () => {
  4. it('should correctly find differences in flat objects', () => {
  5. const oldObj = { a: 1, b: 2, c: 3 };
  6. const newObj = { a: 1, b: 3, c: 3 };
  7. expect(diff(oldObj, newObj)).toEqual({ b: 3 });
  8. });
  9. it('should correctly handle nested objects', () => {
  10. const oldObj = { a: { b: 1, c: 2 }, d: 3 };
  11. const newObj = { a: { b: 1, c: 3 }, d: 3 };
  12. expect(diff(oldObj, newObj)).toEqual({ a: { b: 1, c: 3 } });
  13. });
  14. it('should correctly handle arrays`', () => {
  15. const oldObj = { a: [1, 2, 3] };
  16. const newObj = { a: [1, 2, 4] };
  17. expect(diff(oldObj, newObj)).toEqual({ a: [1, 2, 4] });
  18. });
  19. it('should correctly handle nested arrays', () => {
  20. const oldObj = {
  21. a: [
  22. [1, 2],
  23. [3, 4],
  24. ],
  25. };
  26. const newObj = {
  27. a: [
  28. [1, 2],
  29. [3, 5],
  30. ],
  31. };
  32. expect(diff(oldObj, newObj)).toEqual({
  33. a: [
  34. [1, 2],
  35. [3, 5],
  36. ],
  37. });
  38. });
  39. it('should return null if objects are identical', () => {
  40. const oldObj = { a: 1, b: 2, c: 3 };
  41. const newObj = { a: 1, b: 2, c: 3 };
  42. expect(diff(oldObj, newObj)).toBeNull();
  43. });
  44. it('should return differences between two objects excluding ignored fields', () => {
  45. const oldObj = { a: 1, b: 2, c: 3, d: 6 };
  46. const newObj = { a: 2, b: 2, c: 4, d: 5 };
  47. const ignoreFields: (keyof typeof newObj)[] = ['a', 'd'];
  48. const result = diff(oldObj, newObj, ignoreFields);
  49. expect(result).toEqual({ c: 4 });
  50. });
  51. });