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();
}
}
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;
}
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