最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do you test the content of a div or other element in enzymemochachai? - Stack Overflow

programmeradmin3浏览0评论

I'm trying to verify that the content of a div matches what I'm expecting. 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

I'm trying to verify that the content of a div matches what I'm expecting. 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

Share Improve this question asked Aug 17, 2016 at 17:23 reectrixreectrix 8,62921 gold badges59 silver badges84 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

You can easily setup chai-enzyme https://github./producthunt/chai-enzyme which is very great for things like this. Now you can use:

expect(wrapper.find('.title')).to.have.text('A New Day')

The property you are looking for is 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. 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:

// 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. But react-node ments are relatively straightforward.


p.s. testing props instead is usually a better idea; react's html rendering is already unit-tested by facebook

发布评论

评论列表(0)

  1. 暂无评论