如何用react + enzyme选择元素文本 [英] how to select element text with react+enzyme

查看:148
本文介绍了如何用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,

html 方法返回元素的内容,还返回元素本身以及所有属性,例如它会给出< button class ='btn btn-primary'> OK< / button> 。所以我想,在最坏的情况下,我可以调用 html 并对其进行正则表达式,但是...

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.

推荐答案

不要忘记,您正在将节点(ReactElement)传递给 shallow 函数,并且React中没有HTML属性 class 。您必须使用 className

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.

来自React文档

所有属性均为驼峰式,而 class for 的属性为
className htmlFor 分别匹配DOM API
规范。

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

这篇关于如何用react + enzyme选择元素文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆