Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

reactjs - how to select element text with react+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'); // 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.

question from:https://stackoverflow.com/questions/38277165/how-to-select-element-text-with-reactenzyme

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...