how to select element text with react+enzyme

Kevin picture Kevin · Jul 9, 2016 · Viewed 54.3k times · Source

Just what it says. Some example code:

let wrapper = shallow(<div><button class='btn btn-primary'>OK</button></div>);

const b = wrapper.find('.btn'); 

expect(b.text()).to.be.eql('OK'); // fails,

Also the html method returns the contents of the element but also the element itself plus all the attributes, e.g. it gives <button class='btn btn-primary'>OK</button>. So I guess, worst case, I can call html and regex it, but...

Is there a way to just get the contents of the element, so I can assert on it.

Answer

Nelu picture Nelu · Nov 27, 2018

If you found this while looking for "includes text", try:

it('should show correct text', () => {
  const wrapper = shallow(<MyComponent />);
  expect(wrapper.text().includes('my text')).toBe(true);
});