-
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
1 parent
db3f86b
commit 239903d
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
68 changes: 68 additions & 0 deletions
68
hooks/Array/useArrayReduce/__tests__/useArrayReduce.test.ts
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,68 @@ | ||
import { renderHook } from '@testing-library/react' | ||
import { useArrayReduce } from '../useArrayReduce' | ||
|
||
type Item = { | ||
value: number | ||
} | ||
|
||
const sumReducer = (accumulator: number, current: Item) => { | ||
return accumulator + current.value | ||
} | ||
|
||
describe('useArrayReduce', () => { | ||
it('should calculate the sum correctly', () => { | ||
const items: Item[] = [{ value: 1 }, { value: 2 }, { value: 3 }] | ||
const { result } = renderHook(() => useArrayReduce(items, sumReducer, 0)) | ||
|
||
expect(result.current).toBe(6) | ||
}) | ||
|
||
it('should return the initial value when the list is empty', () => { | ||
const items: Item[] = [] | ||
const { result } = renderHook(() => useArrayReduce(items, sumReducer, 10)) | ||
|
||
expect(result.current).toBe(10) | ||
}) | ||
|
||
it('should correctly handle a complex reducer', () => { | ||
const items: Item[] = [{ value: 1 }, { value: 2 }, { value: 3 }] | ||
const complexReducer = (accumulator: string, current: Item) => { | ||
return `${accumulator}-${current.value}` | ||
} | ||
const { result } = renderHook(() => | ||
useArrayReduce(items, complexReducer, 'init') | ||
) | ||
|
||
expect(result.current).toBe('init-1-2-3') | ||
}) | ||
|
||
it('should return a memoized result for the same input', () => { | ||
const items: Item[] = [{ value: 1 }, { value: 2 }, { value: 3 }] | ||
const { result, rerender } = renderHook( | ||
({ list }) => useArrayReduce(list, sumReducer, 0), | ||
{ | ||
initialProps: { list: items }, | ||
} | ||
) | ||
|
||
const firstResult = result.current | ||
rerender({ list: [...items] }) | ||
|
||
expect(result.current).toBe(firstResult) | ||
}) | ||
|
||
it('should recompute the result when the list changes', () => { | ||
const items: Item[] = [{ value: 1 }, { value: 2 }, { value: 3 }] | ||
const { result, rerender } = renderHook( | ||
({ list }) => useArrayReduce(list, sumReducer, 0), | ||
{ | ||
initialProps: { list: items }, | ||
} | ||
) | ||
|
||
const newItems: Item[] = [{ value: 4 }, { value: 5 }, { value: 6 }] | ||
rerender({ list: newItems }) | ||
|
||
expect(result.current).toBe(15) | ||
}) | ||
}) |