Skip to content

About the author of Daydream Drift

Tomasz Niezgoda (LinkedIn/tomaszniezgoda & GitHub/tniezg) is the author of this blog. It contains original content written with care.

Please link back to this website when referencing any of the materials.

Author:

Safer Object Unit Tests With Object.freeze()

Published

Object mutation in JavaScript is broadly regarded as an anti-pattern and may negatively impact code reliability and maintenance. It should only be allowed in situations where peak performance is required.

When unit testing a function that accepts an object as one of its parameters, it's usually a good idea to make it immutable before invoking the function. It ensures the function does not mutate the supplied object.

To prevent arguments from being tampered with, use Object.freeze(). While this statement won't prevent operations on an object, they will have no effect on it.

Object.freeze() does a shallow freeze. To freeze more elaborate objects, a deep freeze is necessary. JavaScript does not have a built-in function for this, but one can be added manually, for example (taken from here):

function deepFreeze(object) {

  // Retrieve the property names defined on object
  var propNames = Object.getOwnPropertyNames(object);

  // Freeze properties before freezing self
  
  for (let name of propNames) {
    let value = object[name];

    object[name] = value && typeof value === "object" ? 
      deepFreeze(value) : value;
  }

  return Object.freeze(object);
}

var obj2 = {
  internal: {
    a: null
  }
};

deepFreeze(obj2);

obj2.internal.a = 'anotherValue'; // fails silently in non-strict mode
obj2.internal.a; // null