UNPKG

1.11 kBJavaScriptView Raw
1import React, { useState } from 'react';
2import { render, waitForElement, act, cleanup } from '@testing-library/react';
3import { useEffectAsync } from '..';
4
5afterEach(cleanup);
6
7// eslint-disable-next-line react/prop-types
8const 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};
19const asyncFunc = () => Promise.resolve('World');
20
21describe('useEffectAsync', () => {
22 test('should render "Hello" then "World"', async () => {
23 // Create Async Method
24 // Render
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