如何使用testing-library/no-node-access访问props.children

Mat*_*att 6 children eslint react-props testing-library

我已成功安装eslint-plugin-testing-library并使用overrides,因此它仅对测试文件中的代码发出警告。

但是,它抱怨Avoid direct Node access. Prefer using the methods from Testing Library.以下代码props.children

我希望能够插入子节点或默认节点。

return (
  <>
    { // Other elements here. }
    {'children' in props ? (
      props.children
    ) : (
      <MyComponent {...props} disabled={disabled} />
    )}
  </>
)
Run Code Online (Sandbox Code Playgroud)

这段代码有什么问题?为什么 props 被认为是节点访问?我应该如何更改它以满足警告?只需添加// eslint-disable-next-line testing-library/no-node-access

Edit:

这是在测试文件中。它以与主代码相同的方式创建一个元素。我不明白为什么引用props.children会引起警告。我想知道这个警告的理由是什么,以及如何才能达到预期的结果。

Mar*_*rán 6

作者在eslint-plugin-testing-library这里!对于所报道的这种特定行为,我深感抱歉。事实上,props.children这是一种有效的用法,不应报告。您能否将此作为新问题报告?我们以后可以考虑改进这个规则。谢谢!

  • @CodeFinity 这实际上是上述规则旨在防止的情况!您应该查询表树的子级,然后检查是否有 3 个元素。类似于: `const tableChildren = inside(productTableTree).getAllByRole('row'); 期望(tableChildren).toHaveLength(3)` (2认同)