0

I have this Javascript code:

const BaseList = {

  new: function(list) {
    this.list = list;
    return this;
  },

  sortKeys: function(key) {
    const keys = Object.keys(this.list);
    keys.push(key);
    keys.sort();
    return keys;
  }

}

module.exports = BaseList;

and I am testing sortKeys with Mocha/Assert doing this:

describe('#sortKeys', function() {

  it('should insert a new key in order', function() {
    const par = {'a': 'test_a', 'c': 'test_c'};
    const bl = BaseList.new(par);
    const sl = bl.sortKeys('b');
    assert.equal(sl,['a','b','c']);
  });

});

It happens that my test is failing, but the failure message says:

AssertionError [ERR_ASSERTION]: [ 'a', 'b', 'c' ] == [ 'a', 'b', 'c' ]

It seems that we have two equal arrays but the assertion says they are different.

What am I missing here?

Ed de Almeida
  • 3,675
  • 4
  • 25
  • 57

1 Answers1

1

In javascript, Object instances (so Arrays) are never equal, even if they contain same data at the moment. This is because JS compares Objects by reference, not by value.

For a simple solution, just use:

assert.equal(sl.toString(),['a','b','c'].toString());

For a better/more flexible solution: How to compare arrays in JavaScript?

ahoang18
  • 143
  • 7