gpt4 book ai didi

reactjs - 测试时,导致 React 状态更新的代码应该被包装成行为

转载 作者:行者123 更新时间:2023-12-03 15:10:51 25 4
gpt4 key购买 nike

我有这个测试:

import {
render,
cleanup,
waitForElement
} from '@testing-library/react'

const TestApp = () => {
const { loading, data, error } = useFetch<Person>('https://example.com', { onMount: true });

return (
<>
{loading && <div data-testid="loading">loading...</div>}
{error && <div data-testid="error">{error.message}</div>}
{data &&
<div>
<div data-testid="person-name">{data.name}</div>
<div data-testid="person-age">{data.age}</div>
</div>
}
</>
);
};

describe("useFetch", () => {
const renderComponent = () => render(<TestApp/>);

it('should be initially loading', () => {
const { getByTestId } = renderComponent();

expect(getByTestId('loading')).toBeDefined();
})
});

测试通过,但我收到以下警告:

Warning: An update to TestApp inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
/* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser
in TestApp

console.error node_modules/react-dom/cjs/react-dom.development.js:506 Warning: An update to TestApp inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
/* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser
in TestApp

最佳答案

关键是await act然后使用 async箭头函数。

await act( async () => render(<TestApp/>));
来源:
https://stackoverflow.com/a/59839513/3850405

关于reactjs - 测试时,导致 React 状态更新的代码应该被包装成行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56722139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com