Comparing Objects in Chai Doesn’t Work as Expected?
Published 30/05/2016 - Updated 28/07/2023
Table of Contents
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.
Expert advice
You're reading the GL Digital blog, where auto marketing experts share proven tactics to grow your dealership.
Struggling to make good video?
Sometimes it feels like posting on TikTok is a waste of time.
Build a powerful local brand and watch customers roll in from TikTok.