Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 911
reectrix Avatar asked Sep 13 '25 12:09

reectrix


2 Answers

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

like image 177
Henrik R Avatar answered Sep 16 '25 02:09

Henrik R


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
  );
});
like image 36
ken4z Avatar answered Sep 16 '25 00:09

ken4z