-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathact.test.tsx
More file actions
80 lines (61 loc) · 2.4 KB
/
act.test.tsx
File metadata and controls
80 lines (61 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import * as React from 'react';
import { Text } from 'react-native';
import { act, fireEvent, render, screen } from '..';
import { getIsReactActEnvironment } from '../act';
type UseEffectProps = { callback(): void };
const UseEffect = ({ callback }: UseEffectProps) => {
React.useEffect(callback);
return null;
};
const Counter = () => {
const [count, setCount] = React.useState(0);
const text = `Total count: ${count}`;
return <Text onPress={() => setCount(count + 1)}>{text}</Text>;
};
test('render should trigger useEffect', async () => {
const effectCallback = jest.fn();
await render(<UseEffect callback={effectCallback} />);
expect(effectCallback).toHaveBeenCalledTimes(1);
});
test('rerender should trigger useEffect', async () => {
const effectCallback = jest.fn();
await render(<UseEffect callback={effectCallback} />);
await screen.rerender(<UseEffect callback={effectCallback} />);
expect(effectCallback).toHaveBeenCalledTimes(2);
});
test('fireEvent should trigger useState', async () => {
await render(<Counter />);
const counter = screen.getByText(/Total count/i);
expect(counter.props.children).toEqual('Total count: 0');
await fireEvent.press(counter);
expect(counter.props.children).toEqual('Total count: 1');
});
test('should be able to await act', async () => {
const result = await act(async () => {});
expect(result).toBe(undefined);
});
test('should be able to await act when promise rejects', async () => {
await expect(act(() => Promise.reject('error'))).rejects.toBe('error');
});
test('should restore act environment when callback throws synchronously', async () => {
const previousEnvironment = getIsReactActEnvironment();
const testError = new Error('Synchronous error in act');
await expect(
act(() => {
throw testError;
}),
).rejects.toBe(testError);
// Verify the act environment was restored even after error
expect(getIsReactActEnvironment()).toBe(previousEnvironment);
});
test('should restore act environment when callback returns non-promise value', async () => {
const previousEnvironment = getIsReactActEnvironment();
// Call act with a callback that returns a non-promise value
// This tests the else branch in withGlobalActEnvironment
const result = await act(() => {
return 42;
});
expect(result).toBe(42);
// Verify the act environment was restored
expect(getIsReactActEnvironment()).toBe(previousEnvironment);
});