lijianan
2 years ago
committed by
GitHub
1 changed files with 28 additions and 38 deletions
@ -1,48 +1,38 @@ |
|||||
import React, { memo, useContext, useRef, useState } from 'react'; |
import React, { memo, useContext } from 'react'; |
||||
import Row from '../row'; |
import Row from '../row'; |
||||
import RowContext from '../RowContext'; |
import RowContext from '../RowContext'; |
||||
import { render, fireEvent } from '../../../tests/utils'; |
import { fireEvent, pureRender } from '../../../tests/utils'; |
||||
|
|
||||
const CacheInner = memo(() => { |
let innerCount = 0; |
||||
const countRef = useRef(0); |
let outerCount = 0; |
||||
countRef.current++; |
|
||||
useContext(RowContext); |
|
||||
return ( |
|
||||
<div> |
|
||||
Child Rendering Count: <span id="child_count">{countRef.current}</span> |
|
||||
</div> |
|
||||
); |
|
||||
}); |
|
||||
|
|
||||
const CacheOuter = () => { |
const handleClick = () => { |
||||
const [count, setCount] = useState(1); |
outerCount++; |
||||
const handleClick = () => { |
|
||||
setCount(count + 1); |
|
||||
}; |
|
||||
return ( |
|
||||
<div> |
|
||||
<button type="button" onClick={handleClick} id="parent_btn"> |
|
||||
Click |
|
||||
</button> |
|
||||
Parent Rendering Count: <span id="parent_count">{count}</span> |
|
||||
<Row> |
|
||||
<CacheInner /> |
|
||||
</Row> |
|
||||
</div> |
|
||||
); |
|
||||
}; |
}; |
||||
|
|
||||
it('Cached RowContext is working', () => { |
const CacheInner: React.FC = memo(() => { |
||||
const { container } = render(<CacheOuter />); |
innerCount++; |
||||
const childCount = container.querySelector('#child_count')?.textContent; |
useContext(RowContext); |
||||
|
return null; |
||||
|
}); |
||||
|
|
||||
fireEvent.click(container.querySelector('#parent_btn')!); |
const CacheOuter: React.FC = memo(() => ( |
||||
expect(container.querySelector('#parent_count')?.textContent).toBe('2'); |
<> |
||||
// child component won't rerender
|
<button type="button" onClick={handleClick} id="parent_btn"> |
||||
expect(container.querySelector('#child_count')?.textContent).toBe(childCount); |
Click |
||||
|
</button> |
||||
|
<Row> |
||||
|
<CacheInner /> |
||||
|
</Row> |
||||
|
</> |
||||
|
)); |
||||
|
|
||||
|
it('Cached RowContext is working', () => { |
||||
|
const { container, unmount } = pureRender(<CacheOuter />); |
||||
|
expect(outerCount).toBe(0); |
||||
|
expect(innerCount).toBe(1); |
||||
fireEvent.click(container.querySelector('#parent_btn')!); |
fireEvent.click(container.querySelector('#parent_btn')!); |
||||
expect(container.querySelector('#parent_count')?.textContent).toBe('3'); |
expect(outerCount).toBe(1); |
||||
// child component won't rerender
|
expect(innerCount).toBe(1); |
||||
expect(container.querySelector('#child_count')?.textContent).toBe(childCount); |
unmount(); |
||||
}); |
}); |
||||
|
Loading…
Reference in new issue