Testing with Mocha: Array Comparison

December 22, 2014

The Problem

While writing a Mocha test suite for array comparison, I encountered an issue. 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']);

Contrary to my expectations, this test fails, producing the following error:

AssertionError: expected ['a', 'b', 'c'] to equal ['a', 'b', 'c']

My Explanation

Why don't arrays compare like other values? It's because the typeof array is an object. In Mocha, to.equal doesn't indicate that the operands are semantically equal; rather, it checks if they refer to the exact same object. In other words, the test fails because myArray is not the exact same object as ['a', 'b', 'c'].

Possible Solutions

  1. Use .eql for "loose equality" to deeply compare values.
  2. Use .deep.equal, which tests whether the operands are equivalent but not necessarily the same object.
  3. Check .members in the array instead.
  4. Convert the array to a string and then compare.


I hope this revised version better communicates your insights and solutions.

Profile picture

Software development professional with expertise in application architecture, cloud solutions deployment, and financial products development. Possess a Master's degree in Computer Science and an MBA in Finance. Highly skilled in AWS (Certified Solutions Architect, Developer and SysOps Administrator), GCP (Professional Cloud Architect), Microsoft Azure, Kubernetes(CKA, CKAD, CKS, KCNA), and Scrum(PSM, PSPO) methodologies. Happy to connect