|
| 1 | +import { act, renderHook } from '@testing-library/react-hooks'; |
| 2 | +import { replaceRaf } from 'raf-stub'; |
| 3 | +import useRafState from '../useRafState'; |
| 4 | + |
| 5 | +interface RequestAnimationFrame { |
| 6 | + reset(): void; |
| 7 | + step(): void; |
| 8 | +} |
| 9 | + |
| 10 | +declare var requestAnimationFrame: RequestAnimationFrame; |
| 11 | + |
| 12 | +replaceRaf(); |
| 13 | + |
| 14 | +beforeEach(() => { |
| 15 | + requestAnimationFrame.reset(); |
| 16 | +}); |
| 17 | + |
| 18 | +afterEach(() => { |
| 19 | + requestAnimationFrame.reset(); |
| 20 | +}); |
| 21 | + |
| 22 | +describe('useRafState', () => { |
| 23 | + it('should be defined', () => { |
| 24 | + expect(useRafState).toBeDefined(); |
| 25 | + }); |
| 26 | + |
| 27 | + it('should only update state after requestAnimationFrame when providing an object', () => { |
| 28 | + const { result } = renderHook(() => useRafState(0)); |
| 29 | + |
| 30 | + act(() => { |
| 31 | + result.current[1](1); |
| 32 | + }); |
| 33 | + expect(result.current[0]).toBe(0); |
| 34 | + |
| 35 | + act(() => { |
| 36 | + requestAnimationFrame.step(); |
| 37 | + }); |
| 38 | + expect(result.current[0]).toBe(1); |
| 39 | + |
| 40 | + act(() => { |
| 41 | + result.current[1](2); |
| 42 | + requestAnimationFrame.step(); |
| 43 | + }); |
| 44 | + expect(result.current[0]).toBe(2); |
| 45 | + |
| 46 | + act(() => { |
| 47 | + result.current[1](prevState => prevState * 2); |
| 48 | + requestAnimationFrame.step(); |
| 49 | + }); |
| 50 | + expect(result.current[0]).toBe(4); |
| 51 | + }); |
| 52 | + |
| 53 | + it('should only update state after requestAnimationFrame when providing a function', () => { |
| 54 | + const { result } = renderHook(() => useRafState(0)); |
| 55 | + |
| 56 | + act(() => { |
| 57 | + result.current[1](prevState => prevState + 1); |
| 58 | + }); |
| 59 | + expect(result.current[0]).toBe(0); |
| 60 | + |
| 61 | + act(() => { |
| 62 | + requestAnimationFrame.step(); |
| 63 | + }); |
| 64 | + expect(result.current[0]).toBe(1); |
| 65 | + |
| 66 | + act(() => { |
| 67 | + result.current[1](prevState => prevState * 3); |
| 68 | + requestAnimationFrame.step(); |
| 69 | + }); |
| 70 | + expect(result.current[0]).toBe(3); |
| 71 | + }); |
| 72 | + |
| 73 | + it('should cancel update state on unmount', () => { |
| 74 | + const { unmount } = renderHook(() => useRafState(0)); |
| 75 | + const spyRafCancel = jest.spyOn(global, 'cancelAnimationFrame' as any); |
| 76 | + |
| 77 | + expect(spyRafCancel).not.toHaveBeenCalled(); |
| 78 | + |
| 79 | + unmount(); |
| 80 | + |
| 81 | + expect(spyRafCancel).toHaveBeenCalledTimes(1); |
| 82 | + }); |
| 83 | +}); |
0 commit comments