简体   繁体   中英

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. 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. 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 comments are relatively straightforward.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM