What is @types/nock?
@types/nock provides TypeScript type definitions for the nock library, which is used for HTTP mocking and expectations in Node.js applications.
What are @types/nock's main functionalities?
Mocking HTTP Requests
This feature allows you to mock HTTP GET requests to a specified URL and return a predefined response. In this example, a GET request to 'http://example.com/resource' will return a 200 status code with a JSON body.
const nock = require('nock');
const scope = nock('http://example.com')
.get('/resource')
.reply(200, { id: 1, name: 'Resource' });
Intercepting and Modifying Requests
This feature allows you to intercept HTTP POST requests with a specific request body and return a predefined response. In this example, a POST request to 'http://example.com/resource' with a JSON body will return a 201 status code with a JSON response.
const nock = require('nock');
const scope = nock('http://example.com')
.post('/resource', { name: 'New Resource' })
.reply(201, { id: 2, name: 'New Resource' });
Simulating Network Errors
This feature allows you to simulate network errors for HTTP requests. In this example, a GET request to 'http://example.com/resource' will result in a network error.
const nock = require('nock');
const scope = nock('http://example.com')
.get('/resource')
.replyWithError('Network error');
Delay Responses
This feature allows you to introduce a delay before sending the response. In this example, a GET request to 'http://example.com/resource' will be delayed by 2000 milliseconds before returning a 200 status code with a JSON body.
const nock = require('nock');
const scope = nock('http://example.com')
.get('/resource')
.delay(2000)
.reply(200, { id: 1, name: 'Resource' });
Other packages similar to @types/nock
axios-mock-adapter
axios-mock-adapter is a library that allows you to easily mock requests made with axios. It provides a simple API for intercepting requests and returning custom responses. Compared to nock, axios-mock-adapter is specifically designed for axios and may be easier to use if you are already using axios in your project.
fetch-mock
fetch-mock is a library for mocking fetch requests. It provides a flexible API for intercepting fetch requests and returning custom responses. Compared to nock, fetch-mock is specifically designed for the Fetch API and is a good choice if you are using fetch for HTTP requests in your project.
supertest
supertest is a library for testing HTTP servers. It provides a high-level API for making HTTP requests and asserting responses. While supertest is not specifically designed for mocking, it can be used to test HTTP endpoints in a similar way to nock. It is a good choice if you are looking for a more comprehensive testing solution that includes HTTP request testing.