[英]How do you test the content of a div or other element in enzyme/mocha/chai?
I'm trying to verify that the content of a div matches what I'm expecting. 我正在尝试验证div的内容是否符合我的预期。 What I have is:
我有的是:
expect(wrapper.find('div.title').text().to.equal('A New Day');
However, this isn't working for me. 但是,这对我不起作用。 Is this possible in enzyme/chai/mocha?
这可能是酶/柴/摩卡吗?
Thanks 谢谢
You can easily setup chai-enzyme https://github.com/producthunt/chai-enzyme which is very great for things like this. 您可以轻松设置chai-enzyme https://github.com/producthunt/chai-enzyme ,这对于这样的事情非常有用。 Now you can use:
现在你可以使用:
expect(wrapper.find('.title')).to.have.text('A New Day')
The property you are looking for is textContent
您正在寻找的属性是
textContent
expect(wrapper.find('div.title').textContent).to.equal('A New Day');
If you are using chai, which it sounds like you are, you can add a custom assertion. 如果你正在使用chai,它听起来像你,你可以添加自定义断言。 Here is the one I wrote for our project.
这是我为我们的项目写的那个。
// Asserts that the the DOM Element has the expected text
// E.G. expect(myDOMNode).to.have.text('the text');
const text = Assertion.addMethod('text', function(value) {
this.assert(
this._obj.textContent === value,
'expected #{exp} === #{act}',
'expected #{exp} !== #{act}',
this._obj.textContent,
value
);
});
Depending on how much React/JSX you have in your text content, it might be mangled to make simple matching fail: 根据您在文本内容中使用的React / JSX的数量,可能会因为简单匹配失败而受到损坏:
// wrapper.text()
<!-- react-text: 28 -->A <!-- /react-text -->
<!-- react-text: 29 -->New<!-- /react-text -->
<!-- react-text: 30 --> Day<!-- /react-text -->
So if you must test that directly, you can strip them out like so: 因此,如果您必须直接测试,可以将它们剥离出来:
expect(wrapper.text().replace(/<!--[^>]*-->/g, "")).toContain("A New Day");
The regex came from this answer , which warns against regex html. 正则表达式来自这个答案 ,它反对正则表达式html。 But react-node comments are relatively straightforward.
但反应节点评论相对简单。
ps testing props instead is usually a better idea; ps测试道具通常是一个更好的主意; react's html rendering is already unit-tested by facebook
react的html渲染已经由facebook进行了单元测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.