-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
JB AUBREE
committed
Oct 15, 2024
1 parent
df8f2cb
commit 332b375
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
import { polyfillGroupBy } from '../src/polyfill' | ||
|
||
describe('polyfillGroupBy', () => { | ||
beforeEach(() => { | ||
if ('groupBy' in Object) { | ||
delete (Object as { groupBy?: unknown }).groupBy | ||
} | ||
polyfillGroupBy() | ||
}) | ||
|
||
it('should define Object.groupBy if not already defined', () => { | ||
expect(Object.groupBy).toBeDefined() | ||
}) | ||
|
||
it('should group array of objects by a given key', () => { | ||
const array = [ | ||
{ id: 1, category: 'fruit', name: 'apple' }, | ||
{ id: 2, category: 'vegetable', name: 'carrot' }, | ||
{ id: 3, category: 'fruit', name: 'banana' }, | ||
] | ||
const result = Object.groupBy(array, item => item.category) | ||
expect(result).toEqual({ | ||
fruit: [ | ||
{ id: 1, category: 'fruit', name: 'apple' }, | ||
{ id: 3, category: 'fruit', name: 'banana' }, | ||
], | ||
vegetable: [{ id: 2, category: 'vegetable', name: 'carrot' }], | ||
}) | ||
}) | ||
|
||
it('should return an empty object for an empty array', () => { | ||
const result = Object.groupBy([], () => 'key') | ||
expect(result).toEqual({}) | ||
}) | ||
|
||
it('should group by a dynamic key', () => { | ||
const array = [ | ||
{ id: 1, category: 'fruit', name: 'apple' }, | ||
{ id: 2, category: 'fruit', name: 'banana' }, | ||
{ id: 3, category: 'vegetable', name: 'carrot' }, | ||
] | ||
const result = Object.groupBy(array, item => item.name[0]) | ||
expect(result).toEqual({ | ||
a: [{ id: 1, category: 'fruit', name: 'apple' }], | ||
b: [{ id: 2, category: 'fruit', name: 'banana' }], | ||
c: [{ id: 3, category: 'vegetable', name: 'carrot' }], | ||
}) | ||
}) | ||
|
||
it('should not overwrite existing Object.groupBy', () => { | ||
Object.groupBy = vi.fn() | ||
polyfillGroupBy() | ||
expect(Object.groupBy).toBeInstanceOf(Function) | ||
expect(Object.groupBy).toHaveBeenCalledTimes(0) | ||
}) | ||
}) |