Comparing Objects in Chai Doesn’t Work as Expected?

Published 30/05/2016 - Updated 28/07/2023

A profile picture of Gary Lewis Cheetham, the author of this article

Written by

Gary Lewis Cheetham

Automotive marketing specialist from Manchester, UK

Table of Contents [Show]

    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.

    About the author

    A profile picture of Gary Lewis Cheetham, the founder of GL Digital Automotive Marketing, smiling outside a car dealership

    Gary Lewis Cheetham is an automotive marketing specialist, born and raised in Oldham, Greater Manchester. Gary Lewis Cheetham is the founder of GL Digital Automotive Marketing. He spent his teenage years working at the family dealership after school, learning the ropes of the car trade from the inside out.

    After moving on to working in marketing, Gary Lewis founded GL Digital in 2020 when he noticed a need for direct-to-consumer marketing platforms within the auto industry. He now strives every day to help independent dealers in the UK and US realise their potential. Gary also loves Formula 1 and motorsport.