【发布时间】:2023-03-29 20:21:01
【问题描述】:
我正在测试一些代码来计算重新渲染。
这个不起作用,因为我小时候传递<MyComponent>。
it("should get the same object when the parent rerenders", async () => {
jest.useFakeTimers();
const callback = jest.fn();
let renderCount = 0;
let x = 0;
function MyComponent() {
const random = Math.random();
const myRef = useRef({ random })
if (x === 0) {
x = myRef.current.random
}
++renderCount;
callback();
return (<div data-testid="test">{JSON.stringify(myRef.current)}</div>);
}
function MyStateComponent({ children }: PropsWithChildren<{}>) {
const forceUpdate = useReducer(() => ({}), {})[1] as () => void
useEffect(() => {
(async function asyncEffect() {
await delay(10000);
forceUpdate()
})()
}, [])
return (<>{children}</>);
}
const { getByTestId } = render(<MyStateComponent><MyComponent /></MyStateComponent>)
expect(getByTestId("test").textContent).toEqual(JSON.stringify({ random: x }));
expect(renderCount).toEqual(1);
expect(callback).toBeCalledTimes(1);
jest.runAllTimers();
await waitFor(() => {
expect(callback).toBeCalledTimes(2);
expect(getByTestId("test").textContent).toEqual(JSON.stringify({ random: x }));
expect(renderCount).toEqual(2);
});
})
但是,这可行,但我将 <MyComponent /> 嵌入到组件中。
it("should get the same object when the parent rerenders with children", async () => {
jest.useFakeTimers();
const callback = jest.fn();
let renderCount = 0;
let x = 0;
function MyComponent() {
const random = Math.random();
const myRef = useRef({ random })
if (x === 0) {
x = myRef.current.random
}
++renderCount;
callback();
return (<div data-testid="test">{JSON.stringify(myRef.current)}</div>);
}
function MyStateComponent({ children }: PropsWithChildren<{}>) {
const forceUpdate = useReducer(() => ({}), {})[1] as () => void
useEffect(() => {
(async function asyncEffect() {
await delay(10000);
forceUpdate()
})()
}, [])
return (<MyComponent />);
}
const { getByTestId } = render(<MyStateComponent />)
expect(getByTestId("test").textContent).toEqual(JSON.stringify({ random: x }));
expect(renderCount).toEqual(1);
expect(callback).toBeCalledTimes(1);
jest.runAllTimers();
await waitFor(() => {
expect(callback).toBeCalledTimes(2);
expect(getByTestId("test").textContent).toEqual(JSON.stringify({ random: x }));
expect(renderCount).toEqual(2);
});
})
【问题讨论】:
标签: javascript reactjs typescript jestjs