Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select DOM element by text from React component

I'm testing a react component and need to simulate a click on a specific element inside the component. I don't want to add id just for the sake of the test, is there a way to select this element by text?

const ReactTestUtils = require('react-test-utils');
const Sidebar = require('components/sidebar');

describe('clicking on More button', function() {
  it('triggers analytics event', function() {
    const component = renderComponent(<Sidebar policyPreferences={ this.policyPreferences } />);

    const moreButton = component.getDOMElementByText('More'); // <- I need something like this
    ReactTestUtils.Simulate.click(moreButton);

    expect(analytics.track).toHaveBeenCalled();
  }
}
like image 1000
Petr Gazarov Avatar asked Nov 28 '25 13:11

Petr Gazarov


1 Answers

The following function iterates through all elements until it finds one with the matching text:

function getElementByText(text){
    var all = document.getElementsByTagName("*");

    for (var i=0, max=all.length; i < max; i++) {
        if (all[i].innerHTML == text){
            return all[i];
        }
    }
    return null;
}
like image 163
Chris Wissmach Avatar answered Nov 30 '25 03:11

Chris Wissmach