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 badges3 Answers
Reset to default 6You 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