Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select element text with react+enzyme

Tags:

reactjs

enzyme

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'); // fail 

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.

like image 853
Kevin Avatar asked Jul 09 '16 00:07

Kevin


People also ask

How do you find the text of an element in an enzyme?

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.


2 Answers

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); }); 
like image 116
Nelu Avatar answered Sep 22 '22 20:09

Nelu


Don't forget that you are passing a node (ReactElement) to shallow function, and there is no HTML attribute class in React. You have to use className.

From React documentation

All attributes are camel-cased and the attributes class and for are className and htmlFor, respectively, to match the DOM API specification.

This test should works

const wrapper = shallow(<div><button className='btn btn-primary'>OK</button></div>); const button = wrapper.find('.btn');  expect(button.text()).to.be.eql('OK'); 
like image 38
Louis Barranqueiro Avatar answered Sep 19 '22 20:09

Louis Barranqueiro