Fluent Test Data Builder With Overrides

Create readable fixtures with layered overrides, per-item variation and reset support, keeping tests free of duplicated object literals.

JavascriptCli Tooling

Code

javascriptsnippet
36 lines
export function createBuilder(defaults) {
  if (defaults === null || typeof defaults !== "object" || Array.isArray(defaults)) {
    throw new TypeError("defaults must be a plain object");
  }
  const layers = [];
  const build = (overrides = {}) => Object.assign({}, defaults, ...layers, overrides);
  const assertOverrides = (overrides) => {
    if (overrides === null || typeof overrides !== "object" || Array.isArray(overrides)) {
      throw new TypeError("overrides must be a plain object");
    }
  };
  const api = {
    with(overrides) {
      assertOverrides(overrides);
      layers.push(overrides);
      return api;
    },
    reset() {
      layers.length = 0;
      return api;
    },
    build,
    buildList(count, overrides = () => ({})) {
      if (!Number.isInteger(count) || count < 0) {
        throw new RangeError("count must be a non-negative integer");
      }
      if (typeof overrides !== "function") throw new TypeError("overrides must be a function");
      return Array.from({ length: count }, (_, index) => build(overrides(index)));
    },
  };
  return api;
}

const user = createBuilder({ role: "member", active: true });
console.log(user.with({ role: "admin" }).build({ name: "Ada" }));
console.log(user.reset().buildList(2, (index) => ({ id: index + 1 })));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{ role: 'admin', active: true, name: 'Ada' }
[
  { role: 'member', active: true, id: 1 },
  { role: 'member', active: true, id: 2 }
]

Inside the snippet

Count the functions build, assertOverrides and createBuilder as the entire surface area of Fluent Test Data Builder With Overrides.

A guard precedes the TypeError and RangeError: bad state stops the flow there instead of continuing.

Points of care

  • The guard typeof overrides !== "function" short-circuits the flow with an early throw when its condition holds.

Using it

The main signature reads export function createBuilder(defaults)

The surface worth importing is createBuilder; the helpers around it are private to the snippet.

Key statements

return Array.from({ length: count }, (_, index) => build(overrides(index)));
if (typeof overrides !== "function") throw new TypeError("overrides must be a function");
const build = (overrides = {}) => Object.assign({}, defaults, ...layers, overrides);

Interactive Tools for This Topic

FAQ

How does the snippet fail?
Validation comes first — `TypeError` and `RangeError` marks the failure at `typeof overrides !== "function"`, before any partial work happens.
Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `build`, `assertOverrides`, `createBuilder` at load time.