|
1 | | -import { cloneElement, ReactNode, useEffect, useState, Children } from 'react'; |
| 1 | +import { |
| 2 | + cloneElement, |
| 3 | + ReactNode, |
| 4 | + useEffect, |
| 5 | + useState, |
| 6 | + Children, |
| 7 | + useRef, |
| 8 | +} from 'react'; |
2 | 9 | import { renderHook, render, act } from '@testing-library/react'; |
3 | 10 | import { useChildrenWithRefs } from '@pkg/shared'; |
4 | 11 |
|
@@ -29,42 +36,58 @@ describe('useChildrenWithRefs', () => { |
29 | 36 | expect(ref.mock.calls[0][0]).toBe(container.firstChild); |
30 | 37 | }); |
31 | 38 | test('app', () => { |
32 | | - const _refs: HTMLElement[] = []; |
| 39 | + const obj: { ref: HTMLElement | null; refs: HTMLElement[] } = { |
| 40 | + ref: null, |
| 41 | + refs: [], |
| 42 | + }; |
33 | 43 | const App = () => { |
| 44 | + const ref = useRef<HTMLDivElement>(null); |
34 | 45 | const [children, setChildren] = useState<ReactNode>( |
35 | | - <div className="foo">foo</div>, |
| 46 | + <div className="foo" ref={ref}> |
| 47 | + foo |
| 48 | + </div>, |
36 | 49 | ); |
37 | 50 | const [newChildren, refs] = useChildrenWithRefs(children); |
38 | 51 |
|
39 | 52 | useEffect(() => { |
40 | | - _refs.push(...refs); |
| 53 | + obj.refs = refs; |
| 54 | + obj.ref = ref.current; |
41 | 55 | }, [refs]); |
42 | 56 |
|
43 | 57 | return ( |
44 | 58 | <> |
45 | 59 | {newChildren} |
46 | | - <button onClick={() => setChildren(<div className="bar">bar</div>)}> |
| 60 | + <button |
| 61 | + onClick={() => |
| 62 | + setChildren( |
| 63 | + <div className="bar" ref={ref}> |
| 64 | + bar |
| 65 | + </div>, |
| 66 | + ) |
| 67 | + } |
| 68 | + > |
47 | 69 | 切换 children |
48 | 70 | </button> |
49 | 71 | </> |
50 | 72 | ); |
51 | 73 | }; |
52 | 74 |
|
53 | | - expect(_refs).toEqual([]); |
| 75 | + expect(obj.refs).toEqual([]); |
54 | 76 | const { |
55 | 77 | container: { firstChild }, |
56 | 78 | } = render(<App />); |
57 | 79 |
|
58 | 80 | expect(firstChild).toHaveTextContent('foo'); |
59 | 81 | expect(firstChild).toHaveClass('foo'); |
60 | | - expect(_refs.length).toBe(1); |
61 | | - expect(_refs[0]).toBe(firstChild); |
| 82 | + expect(obj.refs.length).toBe(1); |
| 83 | + expect(obj.refs[0]).toBe(firstChild); |
| 84 | + expect(obj.ref).toBe(firstChild); |
62 | 85 |
|
63 | | - _refs.length = 0; |
64 | 86 | act(() => document.querySelector('button')!.click()); |
65 | 87 | expect(firstChild).toHaveTextContent('bar'); |
66 | 88 | expect(firstChild).toHaveClass('bar'); |
67 | | - expect(_refs.length).toBe(1); |
68 | | - expect(_refs[0]).toBe(firstChild); |
| 89 | + expect(obj.refs.length).toBe(1); |
| 90 | + expect(obj.refs[0]).toBe(firstChild); |
| 91 | + expect(obj.ref).toBe(firstChild); |
69 | 92 | }); |
70 | 93 | }); |
0 commit comments