首页 > 解决方案 > 使用 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

标签: reactjsreact-testing-library

解决方案


推荐阅读