Kan*_*nia 5 react-hooks-testing-library
我有相当复杂且仍在增长的应用程序。我们使用带有钩子、上下文和其他有用东西的反应。一般来说,测试 react hooks@testing-library/react-hooks很容易。有时我们会遇到测试通过但出现奇怪警告的情况:
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(() => ...);
Run Code Online (Sandbox Code Playgroud)
这是带有测试的小型应用程序。不幸的是,它仅适用于 chrome。在 FF 上,测试永远不会结束。测试正在通过,但在控制台中是可见的警告。如果它不适合您,请查看图片:
如果有人能向我解释如何摆脱这个警告,我将不胜感激。我尝试了许多不同的方法,但最终,我们的许多测试都抛出了这个警告。
小智 25
我遇到了同样的问题,通过指定像这样的行为的导入来解决
import { renderHook, act } from '@testing-library/react-hooks/dom' // will use react-dom
基于文档https://react-hooks-testing-library.com/installation#renderer
对于您的情况,其他导入选项可能会起作用,具体取决于项目中使用的内容
触发警告是因为依赖链下游的某些东西正在ReactDOM.render直接调用。
在hooks.js你有:
import { useManageNotifications } from "./notifications";
Run Code Online (Sandbox Code Playgroud)
在notifications.js:
import { notification, Alert } from "antd";
Run Code Online (Sandbox Code Playgroud)
antd 的通知包的作用是:
import Notification from 'rc-notification';
Run Code Online (Sandbox Code Playgroud)
如果您扫描几行,您会发现可以通过传递TEST_RENDER属性来告诉该组件使用特定的测试渲染。不幸的是,似乎没有任何方法可以让TEST_RENDER属性通过notificationfromantd并进入Notificationfrom 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
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2239 次 |
| 最近记录: |