1 | import { renderHook } from '@testing-library/react-hooks';
|
2 | import { useOnMount, useOnEvent, deviceInfoEmitter } from '../src/internal/asyncHookWrappers';
|
3 |
|
4 | describe('async-hook-wrappers', () => {
|
5 | let asyncGetter = jest.fn(() => Promise.resolve(true));
|
6 | let initialValue = false;
|
7 | beforeEach(() => {
|
8 | asyncGetter.mockClear();
|
9 | initialValue = Math.random() > 0.5;
|
10 | });
|
11 |
|
12 | describe('useOnMount', () => {
|
13 | it('should exist as a function', () => {
|
14 | expect(typeof useOnMount).toBe('function');
|
15 | });
|
16 | it('should return initial value before effect load', async () => {
|
17 | const { result, waitForNextUpdate } = renderHook(() => useOnMount(asyncGetter, initialValue));
|
18 | expect(result.current).toEqual({ loading: true, result: initialValue });
|
19 | await waitForNextUpdate();
|
20 | });
|
21 |
|
22 | it('should return a new Value after async result obtained', async () => {
|
23 | const { result, waitForNextUpdate } = renderHook(() => useOnMount(asyncGetter, initialValue));
|
24 | await waitForNextUpdate();
|
25 |
|
26 | expect(asyncGetter).toHaveBeenCalled();
|
27 | expect(result.current).toEqual({ loading: false, result: true });
|
28 | });
|
29 | });
|
30 |
|
31 | describe('useOnEvent', () => {
|
32 | const eventName = 'event-hook-event';
|
33 | beforeEach(() => {
|
34 | deviceInfoEmitter.removeAllListeners(eventName);
|
35 | });
|
36 | beforeAll((done) => {
|
37 | done();
|
38 | });
|
39 | it('should exist as a function', () => {
|
40 | expect(typeof useOnEvent).toBe('function');
|
41 | });
|
42 |
|
43 | it('should return a default value before effect load', async () => {
|
44 | const { result, waitForNextUpdate } = renderHook(() =>
|
45 | useOnEvent(eventName, asyncGetter, initialValue)
|
46 | );
|
47 | expect(result.current).toEqual({ loading: true, result: initialValue });
|
48 | await waitForNextUpdate();
|
49 | });
|
50 |
|
51 | it('should return a new Value after async result obtained', async () => {
|
52 | const { result, waitForNextUpdate } = renderHook(() =>
|
53 | useOnEvent(eventName, asyncGetter, initialValue)
|
54 | );
|
55 | await waitForNextUpdate();
|
56 |
|
57 | expect(asyncGetter).toHaveBeenCalled();
|
58 | expect(result.current).toEqual({ loading: false, result: true });
|
59 | });
|
60 |
|
61 |
|
62 | });
|
63 | });
|