gpt4 book ai didi

react-hooks-testing-library - @testing-library/react-hooks 警告 : It looks like you're using the wrong act() around your test interactions

转载 作者:行者123 更新时间:2023-12-04 11:40:18 24 4
gpt4 key购买 nike

我有相当复杂且仍在增长的应用程序。我们使用带有钩子(Hook)、上下文和其他有用东西的 react 。通常,使用 @testing-library/react-hooks 测试 react 钩子(Hook)简单。有时我们会遇到测试通过但出现奇怪警告的情况:

Warning: It looks like you're using the wrong act() around your test interactions.
Be sure to use the matching version of act() corresponding to your renderer:

// for react-dom:
import {act} from 'react-dom/test-utils';
// ...
act(() => ...);

// for react-test-renderer:
import TestRenderer from 'react-test-renderer';
const {act} = TestRenderer;
// ...
act(() => ...);
here正在使用带有测试的小型应用程序。不幸的是,它仅适用于 chrome。在 FF 上,测试永远不会结束。测试正在通过,但在控制台中是可见的警告。如果它不适合您,请查看图片:
codesandbox working example
如果有人能向我解释如何摆脱这个警告,我将不胜感激。我尝试了许多不同的方法,但最终,我们的许多测试都抛出了这个警告。

最佳答案

触发警告是因为依赖链中的某些东西正在调用 ReactDOM.render直接地。
hooks.js你有:

import { useManageNotifications } from "./notifications";
notifications.js :
import { notification, Alert } from "antd";
来自 antd 的通知包做了:
import Notification from 'rc-notification';
这就是 calls ReactDOM.render directly 的组件.
如果您扫描几行,您会发现您可以通过传递 TEST_RENDER 来告诉该组件使用特定的测试渲染。属性(property)。不幸的是,似乎没有任何方法可以获得 TEST_RENDER属性(property)通过 notification来自 antd并进入 Notification来自 rc-notification .
避免触发警告的一种选择是,如果您检测到正在运行测试,则跳过该组件。即保护它的用法,检查 process.env.NODE_ENV在您的 src/notifications.js文件:
    if (process.env.NODE_ENV !== 'test') {
notification[type]({
message: messageIntlId && <b>{messageIntlId}</b>,
description: descriptionIntlId && { descriptionIntlId },
duration: null,
...restProps
});
}

关于react-hooks-testing-library - @testing-library/react-hooks 警告 : It looks like you're using the wrong act() around your test interactions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63472496/

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