How to check whether the element exist using chai?

THpubs picture THpubs · Apr 29, 2016 · Viewed 11.1k times · Source

Using Chai, how can I see whether the element For example, a div with the class .avatar exist?

I tried to.exist but it's not working.

Answer

Nathan Thompson picture Nathan Thompson · Oct 3, 2016

The exist language chain in vanilla Chai is used to verify that a plain old JavaScript object is neither undefined nor null. It sounds like in your case you actually want to be asserting against a DOM element, which vanilla Chai can't do. Instead, you'll need to pull in a Chai plugin like chai-jquery along with jQuery for DOM manipulation. chai-jquery allows you to write assertions against elements you have located using jQuery, and even provides and overriden form of exist that would likely serve your purpose exactly. All together, the code you're looking for to assert a div with class avatar exists would look something like this:

expect($('div.avatar')).to.exist;