jestjs - 如何测试函数在 react-testing-library 中返回 jsx?
问题描述
如何使用 jest/react-testing-library 测试组件是否返回特定的 JSX?
我必须要BeInstanceOf等,但很难找到有关“react-testing-library”的信息
这些是几个例子
const className = props.className;
if (!props.action) {
return props.children;
}
const { id, type, target } = props.action;
if (type === "EXTERNAL") {
return (
<a className={className} href={target}>
{props.children}
</a>
);
}
if (["page"].includes(type.toLowerCase())) {
return (
<Link className={className} key={id} to={"/" + target}>
{props.children}
</Link>
);
}
if (type.toLowerCase() === "play") {
return props.children;
} ...
正如你所看到的,每个回报都是不同的 jsx。
解决方案
理想情况下,您应该寻找面向用户的 DOM 元素,例如文本、标签等。但是,对于此类组件,您可能需要回退到使用测试 ID。您可以添加data-test-id="SomeComponent"
到您要返回的各种元素,然后使用getByTestId
(或queryByTestId
等)查找。
推荐阅读
- python - Airflow Web 界面上没有名为 MySQLdb 的模块
- maven - 即使之前的 maven 命令失败,如何继续执行 Windows 批处理命令?
- r - 无法呈现具有闪亮应用程序的 .Rmd 文件。“错误:未提供 html_dependency 的路径”
- security - 防止 webapi 上的 XSS
- swift - 如何重置 Xcode 模拟器?
- java - 如何解决java spark中的“线程“main”java.lang.Error中的异常:未解决的编译问题:SparkSession无法解析为类型”
- css - 动画就像在队列中一样
- javascript - 脚本验证数组中的数据,然后将您带到另一个页面?
- git - Github PR 拉取请求,包括已在目标分支中的文件
- android-studio - Ironsource 广告未加载“空瀑布”