How to find an element by its text in Enzyme?
The best way I can find to do this, so far, is the following:
const button = wrapper.findWhere(node => {
return (
node.type() &&
node.name() &&
node.text() === "Action 2"
);
});
There must be a name, and a type, to prevent finding a text node.
I'm sure that there must be a better way to do this.
Updated: I'm not sure if Enzyme has changed since I answered this. I see that you can now avoid a text node by checking that node.type()
is not undefined. I'm not sure how you would avoid a parent node with the same text though.
The accepted answer didn't work for me as well - it looks like at least type
should be specified in predicate statement.
So the following one is working for me:
const button = wrapper.findWhere(node => {
return node.type() === 'button' && node.text() === "Action 2";
});
But I'm not sure if this solution is better than the one initially proposed by author.