unique.test.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { describe, expect, it } from 'vitest';
  2. import { uniqueByField } from './unique';
  3. describe('uniqueByField', () => {
  4. it('should return an array with unique items based on id field', () => {
  5. const items = [
  6. { id: 1, name: 'Item 1' },
  7. { id: 2, name: 'Item 2' },
  8. { id: 3, name: 'Item 3' },
  9. { id: 1, name: 'Duplicate Item' },
  10. ];
  11. const uniqueItems = uniqueByField(items, 'id');
  12. // Assert expected results
  13. expect(uniqueItems).toHaveLength(3); // After deduplication, there should be three objects left
  14. expect(uniqueItems).toEqual([
  15. { id: 1, name: 'Item 1' },
  16. { id: 2, name: 'Item 2' },
  17. { id: 3, name: 'Item 3' },
  18. ]);
  19. });
  20. it('should return an empty array when input array is empty', () => {
  21. const items: any[] = []; // Empty array
  22. const uniqueItems = uniqueByField(items, 'id');
  23. // Assert expected results
  24. expect(uniqueItems).toEqual([]);
  25. });
  26. it('should handle arrays with only one item correctly', () => {
  27. const items = [{ id: 1, name: 'Item 1' }];
  28. const uniqueItems = uniqueByField(items, 'id');
  29. // Assert expected results
  30. expect(uniqueItems).toHaveLength(1);
  31. expect(uniqueItems).toEqual([{ id: 1, name: 'Item 1' }]);
  32. });
  33. it('should preserve the order of the first occurrence of each item', () => {
  34. const items = [
  35. { id: 2, name: 'Item 2' },
  36. { id: 1, name: 'Item 1' },
  37. { id: 3, name: 'Item 3' },
  38. { id: 1, name: 'Duplicate Item' },
  39. ];
  40. const uniqueItems = uniqueByField(items, 'id');
  41. // Assert expected results (order of first occurrences preserved)
  42. expect(uniqueItems).toEqual([
  43. { id: 2, name: 'Item 2' },
  44. { id: 1, name: 'Item 1' },
  45. { id: 3, name: 'Item 3' },
  46. ]);
  47. });
  48. });