npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nested-builder

v1.1.1

Published

Tersely construct complex test fixture objects with the builder pattern.

Downloads

81

Readme

Nested builder

When you're testing code that hits an external service, you'll frequently find yourself needing to construct fixture data that's deeply nested. Often, you'll need "valid" data for the full response, but only a small portion of it will be relevant to each specific test. This obfuscates which fields actually are relevant, making the tests harder to read and maintain.

const nock = require("nock");
const {assert} = require("chai");

describe("ComponentUnderTest", function() {
  it("uses the string field", async function() {
    nock("https://api.example.com")
      .get("/resource")
      .reply(200, {
        stringField: "important",
        intField: 0,
      });

    const component = new ComponentUnderTest();
    await component.makeCall();

    assert.strictEqual(component.getState(), "saw the 'important' string");
  });

  it("uses the number field", async function() {
    nock("https://api.example.com")
      .get("/resource")
      .reply(200, {
        stringField: "irrelevant",
        intField: 100,
      });

    const component = new ComponentUnderTest();
    await component.makeCall();

    assert.strictEqual(component.getDoubledInt(), 200);
  });
});

This can quickly get out of hand, especially if response structures are deeply nested, like GraphQL responses. What happens when a field is added or removed?

This package provides the tools to create builder classes that can be used to tersely construct partially specified, deeply nested object structures.

const nock = require("nock");
const {assert} = require("chai");
const {createBuilderClass} = require("nested-builder");

const ResponseBuilder = createBuilderClass()({
  stringField: {default: "irrelevant"},
  intField: {generator: () => Math.random()},
});

describe("ComponentUnderTest", function() {
  it("uses the string field", async function() {
    const r = new ResponseBuilder().stringField("important").build();

    nock("https://api.example.com")
      .get("/resource")
      .reply(200, response);

    const component = new ComponentUnderTest();
    await component.makeCall();

    assert.strictEqual(component.getState(), "saw the 'important' string");
  });

  it("uses the number field", async function() {
    const r = new ResponseBuilder().intField(100).build();

    nock("https://api.example.com")
      .get("/resource")
      .reply(200, r);

    const component = new ComponentUnderTest();
    await component.makeCall();

    assert.strictEqual(component.getDoubledInt(), 200);
  });
});

If you're using TypeScript, builder templates are fully type-checked - each template must specify exactly the same fields as the constructed type, and generated and default values must be of the appropriate kinds.

Installation

Install as a devDependency from npm:

npm install -D nested-builder

Use

The primary entry point is the createBuilderClass function. Use it to construct a builder class by providing a template that describes how to construct unprovided fields.

const ResponseBuilder = createBuilderClass<Response>()({
  fieldZero: {default: 123},
  fieldOne: {generator: generateRandomString},
  fieldTwo: {nested: OtherBuilderClass},
  fieldThree: {plural: true, default: []},
});

Instantiate the builder and use setter methods named after the templated fields to construct only the parts of the object you care about:

const instance = new ResponseBuilder().fieldZero(456).build();

assert.strictEqual(instance.fieldZero, 456);

Setters that correspond to nested field accept a block, which is passed an instance of the appropriate sub-builder:

const instance = new ResponseBuilder()
  .fieldTwo(b => {
    b.otherFieldZero(0);
    b.otherFieldOne(true);
  })
  .build();

assert.strictEqual(instance.fieldTwo.otherFieldZero, 0);
assert.isTrue(instance.fieldTwo.otherFieldOne);

Setters that are plural may be either set as complete Arrays, or constructed piece by piece with a .fieldName.add method:

const ResponseBuilder = createBuilderClass<Response>()({
  fieldZero: {plural: true, default: []},
  fieldOne: {plural: true, nested: OtherBuilder},
});

const instance = new ResponseBuilder()
  .fieldZero([1, 2, 3])
  .fieldOne.add(b => b.otherFieldOne("aaa"))
  .fieldOne.add(b => b.otherFieldOne("bbb"))
  .build();

assert.deepEqual(instance.fieldZero, [1, 2, 3]);
assert.deepEqual(instance.fieldOne, [
  {otherFieldOne: "aaa"},
  {otherFieldOne: "bbb"},
]);