1 | import React, { useState } from 'react';
|
2 | import { render, waitForElement, act, cleanup } from '@testing-library/react';
|
3 | import { useEffectAsync } from '..';
|
4 |
|
5 | afterEach(cleanup);
|
6 |
|
7 |
|
8 | const Component = ({ asyncFunc }) => {
|
9 | const [state, setState] = useState('Hello');
|
10 |
|
11 | useEffectAsync(async () => {
|
12 | const newState = await asyncFunc();
|
13 |
|
14 | act(() => setState(newState));
|
15 | }, []);
|
16 |
|
17 | return <div data-testid="effect-test">{state}</div>;
|
18 | };
|
19 | const asyncFunc = () => Promise.resolve('World');
|
20 |
|
21 | describe('useEffectAsync', () => {
|
22 | test('should render "Hello" then "World"', async () => {
|
23 |
|
24 |
|
25 | const { getByTestId } = render(<Component asyncFunc={asyncFunc} />);
|
26 |
|
27 | // Expect the component to render "Hello"
|
28 | expect(getByTestId('effect-test').textContent).toEqual('Hello');
|
29 |
|
30 | // Wait for the Async Function to be called after mounting
|
31 | await waitForElement(() => getByTestId('effect-test'));
|
32 |
|
33 | // Expect the component to render "World"
|
34 | expect(getByTestId('effect-test').textContent).toEqual('World');
|
35 | });
|
36 | });
|
37 |
|
\ | No newline at end of file |