Search code examples
eslintreact-propschildrentesting-library

How to access props.children with testing-library/no-node-access


I have successfully installed eslint-plugin-testing-library and used overrides so it only warns me on code in test files.

However, it complains Avoid direct Node access. Prefer using the methods from Testing Library. for the following code props.children:

I want to be able to insert children, or a default node.

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

What is wrong with this code? Why is props considered node access? How should I change it to satisfy the warning? Just add // eslint-disable-next-line testing-library/no-node-access?

Edit:

This is in a test file. It is creating an element in the same way as the main code. I do not understand why referencing props.children would warrant a warning. I wonder what is the justification for the warning and how else to perform the desired outcome.


Solution

  • Author of eslint-plugin-testing-library here! I'm sorry about this specific behavior being reported. Indeed, props.children is a valid usage and shouldn't be reported. Could you report this as a new issue? We can take a look at improving this rule in the future. Thanks!