reactjs - 使用 React.cloneElement 测试附加的 html 属性
问题描述
我正在尝试测试一个组件,该组件需要一个孩子并用于将属性React.cloneElement
附加id
到呈现的 HTML。这在浏览器设置中有效,但是在测试期间似乎不起作用。使用 RTL 的debug
函数,我可以看到 jest 渲染的树从不包含附加属性。这是我目前拥有的要点:
// map over the children, set the new component tree as state
const id = "test-cloak"
setTree(React.cloneElement(child, { id, test: "hello" }));
// the component tree now returns the following when logged:
{
'$$typeof': Symbol(react.element),
type: [Function: BasicComponentTree],
key: '.0',
ref: null,
props: { id: 'test-cloak', test: 'hello' },
_owner: null,
_store: {}
}
// when the component is returned, render the new tree conditionally
{tree && <Fragment key={id}>{tree}</Fragment>}
这里最简单的选择是将树包装在一个带有 ID 的元素中,但这并不能满足我需要它做的事情 - 组件应该以一种不会影响任何布局的方式更改传入的子项。包装一个元素可能意味着在其他地方破坏一些 css。
当我运行测试时,这就是我得到的:
<body>
<div>
<div
data-testid="cloak-test"
>
<style>
@media(max-width: 800px) {
#test-cloak {
display: none;
}
}
</style>
// This should have the appended id attribute
<div>
<h1>
Cloak me!
</h1>
</div>
</div>
</div>
</body>
在 React 通过 props 作为属性之后,我该如何测试渲染的 html?我想避免测试 的状态tree
,我真正关心的是属性到达 DOM
解决方案
推荐阅读
- c# - 为所有关键字字段 NEST 添加规范器
- .net - 如何在多个 API 中使用用户信息?
- asp.net-core - ASP.NET Core 3.1“‘用户’不包含‘FindFirstValue’的定义”
- mysql - 如何防止同一用户在 MySQL 中更新自己的记录?
- python - QCombobox 继承背景图像的背景 - PyQt5
- azure - 带有“0”参数的 ExecuteNonQuery”:“从服务器接收结果时发生传输级错误
- python - Node.js 与 python-shell 通信
- continuous-integration - 在多个应用程序之间重复使用相同的 terraform 后端?
- asp.net-mvc - 将许多相似的视图转换为部分视图
- python - 如何使用 FLASK、Python、MySQLdb 将我的登录页面重定向到主页