|
| 1 | +import { useState, useEffect } from 'react' |
| 2 | +import { renderHook, cleanup } from 'src' |
| 3 | + |
| 4 | +describe('async hook tests', () => { |
| 5 | + const getSomeName = () => Promise.resolve('Betty') |
| 6 | + |
| 7 | + const useName = (prefix) => { |
| 8 | + const [name, setName] = useState('nobody') |
| 9 | + |
| 10 | + useEffect(() => { |
| 11 | + getSomeName().then((theName) => { |
| 12 | + setName(prefix ? `${prefix} ${theName}` : theName) |
| 13 | + }) |
| 14 | + }, [prefix]) |
| 15 | + |
| 16 | + return name |
| 17 | + } |
| 18 | + |
| 19 | + afterEach(cleanup) |
| 20 | + |
| 21 | + test('should wait for next update', async () => { |
| 22 | + const { result, waitForNextUpdate } = renderHook(() => useName()) |
| 23 | + |
| 24 | + expect(result.current).toBe('nobody') |
| 25 | + |
| 26 | + await waitForNextUpdate() |
| 27 | + |
| 28 | + expect(result.current).toBe('Betty') |
| 29 | + }) |
| 30 | + |
| 31 | + test('should wait for multiple updates', async () => { |
| 32 | + const { result, waitForNextUpdate, rerender } = renderHook(({ prefix }) => useName(prefix), { |
| 33 | + initialProps: { prefix: 'Mrs.' } |
| 34 | + }) |
| 35 | + |
| 36 | + expect(result.current).toBe('nobody') |
| 37 | + |
| 38 | + await waitForNextUpdate() |
| 39 | + |
| 40 | + expect(result.current).toBe('Mrs. Betty') |
| 41 | + |
| 42 | + rerender({ prefix: 'Ms.' }) |
| 43 | + |
| 44 | + await waitForNextUpdate() |
| 45 | + |
| 46 | + expect(result.current).toBe('Ms. Betty') |
| 47 | + }) |
| 48 | + |
| 49 | + test('should resolve all when updating', async () => { |
| 50 | + const { result, waitForNextUpdate } = renderHook(({ prefix }) => useName(prefix), { |
| 51 | + initialProps: { prefix: 'Mrs.' } |
| 52 | + }) |
| 53 | + |
| 54 | + expect(result.current).toBe('nobody') |
| 55 | + |
| 56 | + await Promise.all([waitForNextUpdate(), waitForNextUpdate(), waitForNextUpdate()]) |
| 57 | + |
| 58 | + expect(result.current).toBe('Mrs. Betty') |
| 59 | + }) |
| 60 | +}) |
0 commit comments