Syndicode presented you several new Node.js tools and now it’s time to meet a new one. When dealing with code that depends on external services maintaining test coverage and writing reliable tests can be challenging. Intercepting and controlling the behavior of external HTTP requests returns reliability to our tests. This is where Nock comes in. Nock is an HTTP server mocking and expectations library for Node.js.
Nock can be used to test modules that perform HTTP requests in isolation. For instance, if a module performs HTTP requests to a CouchDB server or makes HTTP requests to the Amazon API, you can test that module in isolation. Nock works by overriding Node’s
http.request function. Also, it overrides
http.ClientRequest too to cover for modules that use it directly.
Nock allows us to avoid the mentioned challenges by intercepting external HTTP requests and enabling us to either return custom responses to test different scenarios, or store real responses as ‘fixtures’, canned data that will return reliable responses.
Explore the Nock functions here.