concept nock in category javascript

appears as: nock
Testing JavaScript Applications

This is an excerpt from Manning's book Testing JavaScript Applications.

Mocking can be a fantastic solution when you’re interacting with applications over other protocols, like MQTT or CoAP, but, for HTTP, you can use a module called nock.

Instead of requiring you to determine the sender library’s behaviour, as the previous mocks did, nock requires you to determine the server’s response. By using nock, your tests won’t rely on the behaviour of the library you’re using to make requests. Because you will mock the server’s response, your tests will be more loosely coupled, and, therefore, cheaper.

Install nock as a dev-dependency so that you can use it in your tests.

The nock package will let you specify which should be the status and the response for a particular HTTP verb, domain, path, and query string.

Listing 4.61. server.test.js
const nock = require("nock");

// Don't forget to remove the mock you've done for `isomorphic-fetch`!

// ...

beforeEach(() => nock.cleanAll());  #1

describe("fetch inventory items", () => {
  // ...

  test("can fetch an item from the inventory", async () => {
    const eggsResponse = {
      title: "FakeAPI",
      href: "example.org",
      results: [{ name: "Omelette du Fromage" }]
    };

    nock("http://recipepuppy.com")  #2
      .get("/api")
      .query({ i: "eggs" })
      .reply(200, eggsResponse);

    const response = await request(app)  #3
      .get(`/inventory/eggs`)
      .expect(200)
      .expect("Content-Type", /json/);

    expect(response.body).toEqual({  #4
      ...eggs,
      info: `Data obtained from ${eggsResponse.title} - ${eggsResponse.href}`,
      recipes: eggsResponse.results
    });
  });
});

With nock you won’t need to manually write assertions to check whether the fetch function sent requests to other inappropriate endpoints. Any requests sent to URLs other than the ones you mocked with nock will cause the test to fail.

Now that you have a form to submit items, you don’t need to manually call addItem and updateItemList in your main.js file anymore. Instead, you can replace the entire content of this file, and only make it attach an event listener to the form.