Codecademy: assert.deepEqual()

Photo by fabio on Unsplash

Codecademy: assert.deepEqual()

Explaining how/why assert.deepEqual evaluates to true

Overall this Codecademy lesson on assert.deepEqual does a good job of explaining what I imagine to be a very basic example of how to use deepEqual.

At the end of the guided lesson the code looks as follows:

const assert = require('assert');

describe('+', () => {
  it('returns the sum of two values', () => {
    // Setup
    let expected = {a: 3, b: 4, result: 7}; // Line 6
    let sum = {a: 3, b: 4}; // Line 7

    // Exercise
    sum.result = sum.a + sum.b; // Line 10

    // Verify
    assert.deepEqual(sum, expected); // Line 13
  });
});

A beginner or intermediate level learner with knowledge of how objects work can probably read through the code and understand what is happening (i.e. why assert.deepEqual evaluates to true) though it isn't immediately apparent.

So, why does assert.deepEqual evaluate to true?

  1. [Lines 6-7] The expected object has length 3, and the sum object has length 2
  2. [Line 10] sum.result = sum.a + sum.b adds a new key-value pair (result: 7) to the sum object.
  3. Because of Line 10, the sum object now also has length 3, and each key-value pair is the same across both objects
  4. [Line 13] assert.deepEqual evaluates to true

Or, in commented form:

const assert = require('assert');

describe('+', () => {
  it('returns the sum of two values', () => {
    // Setup
    let expected = {a: 3, b: 4, result: 7};
    let sum = {a: 3, b: 4};

    // Exercise
    sum.result = sum.a + sum.b;
    // At this point sum = {a: 3, b: 4, result: 7} 
    // (which is the same as expected)

    // Verify
    assert.deepEqual(sum, expected);
  });
});