Hello and welcome to Continuous Improvement, the podcast where we explore common development issues and find solutions for them. I’m your host, Victor, and today we’re going to talk about an interesting problem that I encountered while writing a Mocha test suite for array comparison.

So, I had this simple test suite for array comparison that should return true if two arrays have the same values. Here’s the code:

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']);
  });
});

Now, you would expect this test to pass, right? After all, the arrays have the same values. But, to my surprise, the test failed with an AssertionError. Here’s the error message:

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

So, I started digging into the problem and here’s what I found. Arrays in JavaScript are considered as objects in terms of their data type. That’s why when we use the to.equal assertion in Mocha, it checks if the two operands are the exact same object, not just semantically equal.

Understanding this, I came up with a few possible solutions. The first one is to use .eql, which stands for “loose equality”. This allows us to deeply compare the values of the arrays. Another option is to use .deep.equal, which checks if the operands are equivalent but not necessarily the same object. Alternatively, you can also check the .members in the array instead. And lastly, you can convert the array to a string and then compare.

Now, if you’re interested in exploring these solutions further, I highly recommend checking out the references I found helpful. They are the ChaiJS BDD API Arguments Section and the ChaiJS BDD API Members Section.

And that concludes today’s episode of Continuous Improvement. I hope you found this discussion insightful and helpful for your own development journey. If you have any topics or issues you’d like me to cover in future episodes, feel free to reach out to me.

Thank you for listening, and until next time, keep improving!