A comprehensive HTTP server mocking and expectations library for Node.js to test modules in isolation.
Nock is an HTTP server mocking and expectations library for Node.js that intercepts and simulates HTTP requests. It allows developers to test modules that rely on external APIs or services in isolation by mocking their responses without making actual network calls. This ensures tests are fast, reliable, and independent of external dependencies.
Node.js developers writing unit or integration tests for applications that make HTTP requests, such as API clients, microservices, or modules interacting with third-party services like CouchDB or Amazon APIs.
Developers choose Nock for its comprehensive feature set, including precise request matching, flexible response simulation, and recording capabilities. It integrates seamlessly with Node's HTTP stack, provides detailed expectation tracking, and is widely adopted in the Node.js ecosystem for reliable test isolation.
HTTP server mocking and expectations library for Node.js
Nock intercepts requests based on hostname, path, method, query strings, headers, and body using strings, regex, or functions, as detailed in the 'Specifying hostname' and 'Specifying path' sections.
It can reply with static data, JSON, files, streams, or dynamic callbacks, including custom status codes and headers, enabling realistic mock setups without network calls.
Methods like .isDone() and .pendingMocks() help ensure all mocked requests are made, preventing false positives in tests, as explained in the 'Expectations' section.
The Nock Back feature records real HTTP interactions to generate fixtures for playback, simplifying test maintenance and setup, covered in the 'Recording' and 'Nock Back' sections.
The README admits requests from ES modules aren't intercepted unless Node is preloaded with Nock via --import flag, adding complexity for modern codebases.
Nock can cause memory issues in Jest tests if nock.restore() isn't called after each suite, requiring manual cleanup that's easy to overlook.
Using Nock with Axios requires setting axios.defaults.adapter and adjusting Jest configs, as noted in the 'Axios' section, adding setup friction.
JavaScript API for Chrome and Firefox
Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
Delightful JavaScript Testing.
☕️ Classic, reliable, trusted test framework for Node.js and the browser
Open-Awesome is built by the community, for the community. Submit a project, suggest an awesome list, or help improve the catalog on GitHub.