Back in JS101: Equality I wrote about the difference between
deepEqual and how it works.
Deep equality is defined in CommonJS Unit Testing/1.0, under subsection 7. The algorithm assumes two arguments:
actual. The purpose of the algorithm is to determine if the values are equivalent. It supports both primitive values and objects.
- Strict equals (
===) means the values are equivalent
- Compare dates using the
- If values are not objects, compare with
- Otherwise, compare each object's size, keys, and values
== because they're primitive values (Undefined, Null, Boolean, Number, or String).
The second step works because
getTime is the most convenient way of comparing dates:
var assert = require('assert') , a = new Date(2012, 1, 1) , b = new Date(2012, 1, 1) ; assert.ok(a !== b); assert.ok(a != b); assert.ok(a.getTime() == b.getTime()); assert.deepEqual(a, b);
This script can be run in Node, or with a suitable CommonJS assertion library. It illustrates the point that dates are not considered equal using the equality or strict equality operators -- the easiest way to compare them is with
Object comparison implies recursion, as some values may also be objects. Also, key comparison isn't as simple as it might seem: real implementations sort keys, compare length, then compare each value.
Bugs have been found in the Unit Testing/1.0 specification since it originally appeared. Two have been flagged up on the main Unit Testing page. The Node
assert module addresses these points. For example, regular expressions are a special case in the
return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase;
source property has a string that represents the original regular expression, and then each flag has to be compared.
The next time you're writing a test, or even just comparing objects, remember that
== will only work for "shallow" comparisons. Testing other values like arrays, dates, regular expressions, and objects requires a little bit more effort.