I have multiple buttons on my page:
<div>
<h1>Home</h1>
<button>Action 1</button>
<button>Action 2</button>
</div>
How can I select the "Action 2" button by its text, so that I can click on it? I know that there may be other ways to select that button, but I am specifically looking for the best way to select an element by its text.
One way I have found is shown below. Is there a better way?
const action2Button = wrapper.find('button[children="Action 2"]');
expect(action2Button).toHaveLength(1);
action2Button.simulate('click');
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With