我正在测试反应组件,需要模拟组件内部特定元素的点击。我不想仅仅为了测试而添加id
,有没有办法按文本选择这个元素?
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();
}
}
答案 0 :(得分:4)
以下函数遍历所有元素,直到找到具有匹配文本的元素:
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;
}