Either its a bug or it probably should be documented that this prop does not work
let wrapper = shallow(<div><div key="foo" /></div>)
expect(wrapper.contains(<div key="foo" />)).toEqual(true) // No error
expect(wrapper.find('[key="foo"]').length).toEqual(1) // Error: Expected 0 to equal 1
expect(wrapper.find({key:"foo"}).length).toEqual(1) // Error: Expected 0 to equal 1
This is intentional. "key" is not a real prop, it's a magic thing React uses to identify array items.
In other words, you need to use a different name than "key".
You can read more about key here: https://facebook.github.io/react/docs/lists-and-keys.html#keys
It would be nice if this is mentioned in the doc ( http://airbnb.io/enzyme/docs/api/selector.html ).
enzyme docs naturally assume that you've previously read the React docs; but sure, a PR to make our docs link to the React docs on "key" and "ref" would be great.
As someone who has read the React docs and worked with it extensively, I'd like to say:
key would not be usable in a selector, since key isn't mentioned and since enzyme is specifically designed to work with React.key, since again enzyme is specifically designed to work with react, but I understand your decision & just wish it were better documented.You can do this instead:
wrapper.findWhere(node => node.key() === 'foo');
I'd like to second point 2) of @melinath 's post above - key is _exactly_ the kind of thing which we _should_ be able to select on, since the use case for wanting to search on it (you have multiple instances of the same component) is precisely the same case in which react forces you to have it (and forces it to be unique, making it a good selector).
It would great if enzyme would reconsider this decision.
@lobsterkatie per https://github.com/airbnb/enzyme/issues/645#issuecomment-375730611, you can already do this - just using findWhere, not find.
One issue I ran into using the findWhere() approach is that you will get errors when the current node isn't an element. I just wrote a function to check for that though.
@WalterWeidner n && n.whatever should handle that?
What about testing the key prop to match a specific value using something like:
expect(
wrapper.contains([<A key={id} />, <B key={id} />])
).toBeTruthy()
You could simply pass the same id to all the Nodes and it is going to work when it should not.
Add an id (or some other identifier) to your div, or even better create a component
let wrapper = shallow(
<div>
<div id="fooId" key="foo" />
</div>
);
Then use standard findto get the key function instead of findWhere
expect(wrapper.find("#fooId").key()).toBe("foo");
Most helpful comment
As someone who has read the React docs and worked with it extensively, I'd like to say:
keywould not be usable in a selector, sincekeyisn't mentioned and since enzyme is specifically designed to work with React.key, since again enzyme is specifically designed to work with react, but I understand your decision & just wish it were better documented.