enzymejs / enzyme-matchers

Jasmine/Jest assertions for enzyme
MIT License
892 stars 116 forks source link

When Components pass props onto dom nodes, it is impossible to select the nodes. #286

Closed conartist6 closed 5 years ago

conartist6 commented 5 years ago

In the application I work on, this is a common pattern as well as, in my opinion, a general best practice:

const Button = props => {
  const { baz, quux, ...elementProps };
  // ...
  return <button ...elementProps />;
}

The problem is that it makes the resulting element impossible to use due to a combination of enzyme behavior and enzyme-matchers behavior.

The problem is that when a usage like <Button id="foo" /> occurs, any enzyme selector like "#foo" will now return two elements instead if 1. It is apparently intended (if misguided, IMO) behavior that for purposes of RN support #foo also functions exactly like {id: "foo"}. Also [attr="value"] is like {[attr]: value}.

In order to work around this you must call .find(selector).hostNodes() in order to discard the undesired result. Unfortunately when you used enzyme-matchers, you cede control of the call to find and thus the ability to call hostNodes. This means whatever property you use to identify elements for testing (except perhaps extra class names, which seems dirty in this day and age) will be unusable if it is attached to the element with the same name it has in the component's props.

blainekasten commented 5 years ago

@conartist6 I definitely understand and personally agree that this is a shortcoming of enzyme. I am struggling to understand how enzyme-matchers is part of this or how enzyme-matchers could make this simpler. Definitely open to feedback here. I think the issue is primarily in the way Enzyme was designed.

If I remember correctly, what you described is the behavior of mount, whereas I believe the behavior of shallow will not keep the wrapping component as part of the render tree.

That said, I'm not really sure what the actionable steps are here, and it seems as this is a more of an edge case that has many work arounds. But I am happy to hear your opinions on ideas to improve this.

conartist6 commented 5 years ago

The more I think about it the more I think it's their problem not yours.