开玩笑的快照测试等待直到组件渲染
我觉得在测试与异步提取操作的React组件时缺少一些东西。
我有这样的以下组件...
export default function Page() {
const [result, setResult] = useState();
async function initialize() {
const response = api.fetchData();
setResult(response);
}
useEffect(() => {
initialize();
}, []);
return (isLoading ? (
<div>Fetching Data...</div>
) : (
<div className="page-result-name">{result.name}</div>
)
}
我想创建以下测试。
test('Page rendering test.', async () => {
jest.spyOn(api, 'fetchData').mockResolvedValue({ name: 'User 1'});
const pageRendering = renderer.create(<Page />);
// Wait? How to wait?
// I have tried the following... as well as other method.
// await waitFor(() => {
// const element = document.getElementByClassName('page-result-name')[0] as
// HTMLElement;
// expect(element.innerHTML.includes('User 1')).toBeTruthy();
// });
expect(pageRendering.toJSON()).toMatchSnapshot();
});
我遇到的问题是,在拍摄快照时尚未返回数据。
无论方法如何,我都遇到了以下警告问题
Warning: It looks like you're using the wrong act() around your test interactions
,或者它总是显示获取数据...
我使用 @testing-library/react的渲染以及waitfor和一切正常。我不知道如何为此生成快照。
这里的任何帮助将不胜感激!!
干杯!!
I feel like I am missing something when it comes to testing React components with async fetch operations.
I have a following component like this...
export default function Page() {
const [result, setResult] = useState();
async function initialize() {
const response = api.fetchData();
setResult(response);
}
useEffect(() => {
initialize();
}, []);
return (isLoading ? (
<div>Fetching Data...</div>
) : (
<div className="page-result-name">{result.name}</div>
)
}
I want to create the following test.
test('Page rendering test.', async () => {
jest.spyOn(api, 'fetchData').mockResolvedValue({ name: 'User 1'});
const pageRendering = renderer.create(<Page />);
// Wait? How to wait?
// I have tried the following... as well as other method.
// await waitFor(() => {
// const element = document.getElementByClassName('page-result-name')[0] as
// HTMLElement;
// expect(element.innerHTML.includes('User 1')).toBeTruthy();
// });
expect(pageRendering.toJSON()).toMatchSnapshot();
});
The issue I am running into is that the data has not been returned by the time the snapshot is taken.
Regardless of the approach I run into issues with warnings like the following
Warning: It looks like you're using the wrong act() around your test interactions
Or it always displays Fetching Data...
I have used render from @testing-library/react and the waitFor and things work well. I don't know how to generate a snapshot for that.
Any help here would be appreciated!!
Cheers!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于异步操作,棘手的是等待从屏幕上删除加载组件,这样您就可以确保组件已完成,然后您可以期望快照:
For async operations the tricky is waiting for loading component to be removed from the screen, this way you assure that the your component is completed loaded and then you can expect the snapshot: