Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element by its text in Enzyme?

Tags:

enzyme

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');
like image 777
Naresh Avatar asked May 20 '19 20:05

Naresh


2 Answers

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.

like image 188
Dzmitry Alifer Avatar answered Oct 15 '22 07:10

Dzmitry Alifer


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.

like image 39
gburnett Avatar answered Oct 15 '22 05:10

gburnett