1 min read

Comparing Objects in Chai Doesn't Work as Expected?

Here's the gotcha of all gotchas.

If you compare two objects in Chai with .equal, you're not going to get what you expected.

These two objects are clearly equal, however the test fails:

× should equal
  PhantomJS 2.1.1 (Windows 8 0.0.0)
expected { Object (name, species, ...) } to equal { Object (name, species, ...) }

What's going wrong here? Use to.deep.equal. An equivalent method is to.eql, but I personally find the latter more readable.

When comparing objects, Chai needs to know that it must traverse the objects and compare nested properties. That's why the deep flag is needed for object comparison.

I hope you enjoyed this article, if you have anything you'd like to add or would otherwise like to get in touch, you can do so on twitter @glcheetham.

Join the Adstronauts 🪐

Talk is cheap, online advertising isn't. Every week I'll send you actionable tips to grow your Shopify business.

No spam ever. Unsubscribe anytime.