Victor Leung
Victor Leung
BlogAI SolutionAlphaAlgoFlower shopFX CombineIEESushi ClassifierWealth Agile

Testing with Mocha: Array Comparison

December 22, 2014

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-sectionhttp://chaijs.com/api/bdd/#members-section


About Victor Leung

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
LinkedIn
Github
Twitter
@victorleungtw

Continuous improvement

Copyright © victorleungtw.com 2023.