-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseEnsuredForwardedRef.test.tsx
74 lines (55 loc) · 1.95 KB
/
useEnsuredForwardedRef.test.tsx
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
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
import { renderHook } from '@testing-library/react-hooks';
import TestUtils from 'react-dom/test-utils';
import { ensuredForwardRef, useEnsuredForwardedRef } from '../src';
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null!;
});
test('should return a valid ref with existing forwardedRef', () => {
const { result } = renderHook(() => {
const ref = useRef(null);
const ensuredRef = useEnsuredForwardedRef(ref);
TestUtils.act(() => {
ReactDOM.render(<div ref={ensuredRef} />, container);
});
return {
initialRef: ref,
ensuredForwardedRef: ensuredRef,
};
});
const { initialRef, ensuredForwardedRef } = result.current;
expect(ensuredForwardedRef).toStrictEqual(initialRef);
});
test('should return a valid ref when the forwarded ref is undefined', () => {
const { result } = renderHook(() => {
const ref = useEnsuredForwardedRef<HTMLDivElement>(undefined!);
TestUtils.act(() => {
ReactDOM.render(<div id="test_id" ref={ref} />, container);
});
return { ensuredRef: ref };
});
const { ensuredRef } = result.current;
expect(ensuredRef.current.id).toBe('test_id');
});
test('should return a valid ref when using the wrapper function style', () => {
const { result } = renderHook(() => {
const initialRef = useRef<HTMLDivElement | null>(null);
const WrappedComponent = ensuredForwardRef<HTMLDivElement>((_props, ref) => {
return <div id="test_id" ref={ref} />;
});
TestUtils.act(() => {
ReactDOM.render(<WrappedComponent ref={initialRef} />, container);
});
return { initialRef };
});
const { initialRef } = result.current;
expect(initialRef.current).toBeTruthy();
expect(initialRef.current?.id).toBe('test_id');
});