Testing with Mocha: Array Comparison

The problem

I was writing a mocha test for an array comparison. Here is the test suite:

describe(‘Array comparison’, function () { ‘use strict’; it(‘should return true if two arrays have the same values’, function () { var myArray = [ ‘a’, ‘b’, ‘c’ ]; expect(myArray).to.equal([ ‘a’, ‘b’, ‘c’ ]); }); });

However, out of my expectation, this test would fail:

AssertionError: expected [ ‘a’, ‘b’, ‘c’ ] to equal [ ‘a’, ‘b’, ‘c’ ]

My Explanation

Why do arrays not compare the way other values do? Because typeof array is an object. In mocha, to.equal does not signify that the operands are semantically equal, but they refer to the exact same object. In other words, the above test fails since myArray is not the exact same object as [ ‘a’, ‘b’, ‘c’ ];

Possible Solutions

  1. Use .eql for ‘lose equality’ in order to deeply compare values.
  2. Use .deep.equal, which does not test whether the operands are the same object, but rather that they are equivalent.
  3. Check .members in the array instead
  4. Convert the array to string and compare it.

References

http://chaijs.com/api/bdd/#arguments-section http://chaijs.com/api/bdd/#members-section

Originally published at victorleungtw.com on November 28, 2014.

By Victor Leung

Experience in software development, consulting services and technical product management. Understanding of business and technology with an MBA in Finance and a Master degree in Computer Science. AWS Certified Solution Architect with experience in building products from scratch and serving as a charismatic leader.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.