Difference between assert.equal and assert.deepEqual in testing Javascript with Mocha?

I use Mocha to test a small module in an Express.js application. In this module, one of my functions returns an array. I want to check the correctness of an array for a given input. I do like this:

suite('getWords', function(){ test("getWords should return list of numbers", function() { var result = ['555', '867', '5309']; assert.equal(result, getWords('555-867-5309')); }); }); 

When this is done, I get the following statement error:

 AssertionError: ["555","867","5309"] == ["555","867","5309"] 

However, when I change my test to assert.deepEqual , the test passes fine. I was wondering if this was the case == vs === , but if I introduce

 [1,2,3] === [1,2,3] 

on the node.js command line, I still get false.

Why don't arrays compare how other values ​​do it (e.g. 1 == 1 )? and what is the difference between assert.equal and assert.deepEqual? A.

+52
javascript arrays testing mocha
Nov 05
source share
1 answer

Why don't arrays compare how other values ​​do it (e.g. 1 == 1)

Numbers, strings, booleans, null and undefined are values ​​and are compared, as you might expect. 1 == 1 , 'a' == 'a' , etc. The difference between === and == in the case of values ​​is that == will try to perform type conversion first, therefore '1' == 1 , but not '1' === 1 .

Arrays, on the other hand, are objects. === and == in this case do not mean that the operands are semantically equal, but they refer to the same object.

What is the difference between assert.equal and assert.deepEqual? A.

assert.equal behaves as described above. In fact, this fails if the arguments are != , As you can see in the source . Thus, it is not suitable for your arrays of numbers, because although they are essentially equivalent, they are not the same object.

On the other hand, deep (aka structural) equality does not check whether the operands are the same object, but rather equivalent. In a sense, you could say that it makes objects compare as if they were values.

 var a = [1,2,3] var b = a // As a and b both refer to the same object a == b // this is true a === b // and this is also true a = [1,2,3] // here a and b have equivalent contents, but do not b = [1,2,3] // refer to the same Array object. a == b // Thus this is false. assert.deepEqual(a, b) // However this passes, as while a and b are not the // same object, they are still arrays containing 1, 2, 3 assert.deepEqual(1, 1) // Also passes when given equal values var X = function() {} a = new X b = new X a == b // false, not the same object assert.deepEqual(a, b) // pass, both are unadorned X objects b.foo = 'bar' assert.deepEqual(a, b) // fail! 
+103
Nov 05
source share



All Articles