concept nock in category javascript

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
MQTTorCoAP, but, for HTTP, you can use a module callednock.Instead of requiring you to determine the sender library’s behaviour, as the previous mocks did,
nockrequires you to determine the server’s response. By usingnock, 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
nockas a dev-dependency so that you can use it in your tests.The
nockpackage 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
nockyou won’t need to manually write assertions to check whether thefetchfunction sent requests to other inappropriate endpoints. Any requests sent to URLs other than the ones you mocked withnockwill cause the test to fail.
Now that you have a form to submit items, you don’t need to manually call
addItemandupdateItemListin yourmain.jsfile anymore. Instead, you can replace the entire content of this file, and only make it attach an event listener to the form.