Reactjs 使用React.cloneElement测试附加的html属性
我正在尝试测试一个组件,该组件使用Reactjs 使用React.cloneElement测试附加的html属性,reactjs,react-testing-library,Reactjs,React Testing Library,我正在尝试测试一个组件,该组件使用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, {
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>}
//映射子级,将新组件树设置为状态
const id=“测试斗篷”
setTree(React.cloneElement(子,{id,test:“hello”}));
//组件树现在在记录时返回以下内容:
{
“$$typeof”:符号(react.element),
类型:[函数:BasicComponentTree],
键:'.0',
ref:null,
道具:{id:'测试斗篷',测试:'你好'},
_所有者:空,
_存储:{}
}
//返回组件时,有条件地呈现新树
{tree&&{tree}
这里最简单的选择是将树包装在一个带有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>
@介质(最大宽度:800px){
#测试斗篷{
显示:无;
}
}
//这应该具有附加的id属性
掩护我!
在React作为属性通过道具之后,如何测试呈现的html?我希望避免测试树的状态,我真正关心的是属性到达DOM