Hock: HTTP Mocking Server

raw JSON →
1.4.1 verified Thu Apr 23 auth: no javascript abandoned

Hock is an HTTP mocking server designed for Node.js applications, enabling the definition of mock HTTP requests and their corresponding responses to facilitate testing. Unlike Nock, which intercepts `http.clientRequest`, Hock functions as a self-contained, fully operational HTTP service, making it suitable for integration tests that require a network endpoint to be hit. The package's API is intentionally similar to Nock's, allowing for familiar patterns in defining request expectations and responses. The current stable version is 1.4.1, last updated over eight years ago. The project appears to be unmaintained, evidenced by its reliance on deprecated Node.js versions (>=0.8.x) and older, unmaintained dependencies like `request`. Due to its age and lack of maintenance, it is generally not recommended for new projects or environments running modern Node.js.

error require is not defined
cause Attempting to use `hock` (a CommonJS module) in an ES Modules context (e.g., in a file where `type: module` is set in `package.json` or a `.mjs` file).
fix
Either use CommonJS syntax (const hock = require('hock');) in a CommonJS file, or refactor your project to use an ESM-compatible mocking library. If forced to use hock in an ESM project, consider dynamic import (import('hock')).
error TypeError: hock.createHock is not a function
cause Incorrectly trying to destructure `createHock` from the `hock` module, e.g., `const { createHock } = require('hock');`.
fix
The createHock function is a method of the default hock export object. Access it via const hock = require('hock'); const mock = hock.createHock();
error Error: unable to verify the first certificate
cause Older Node.js versions or libraries (like the deprecated `request` used by `hock`) may have issues with modern SSL certificates and cipher suites, especially when making requests to HTTPS endpoints that use newer security standards.
fix
Ensure your environment has up-to-date CA certificates. As a temporary workaround for testing, you might try process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; (use with caution, only in development/testing, and understand the security implications), or try downgrading Node.js if compatibility with hock is critical and this error is related to Node.js's crypto module.
deprecated The `hock` package is unmaintained, with its last release over eight years ago. It relies on the deprecated `request` library, which is no longer actively developed and may have security vulnerabilities or compatibility issues with modern Node.js environments.
fix Consider using actively maintained alternatives like `nock` or a dedicated test server with more recent mock capabilities if possible. If you must use `hock`, be aware of potential security risks and use a specific, pinned version.
gotcha Hock is a CommonJS module and does not natively support ES Modules (`import/export` syntax). Attempting to import it using ES Module syntax will result in runtime errors.
fix Always use `const hock = require('hock');` to import the library in your Node.js projects.
gotcha The package targets Node.js versions `>=0.8.x`, which are extremely old and no longer supported. Running `hock` on modern Node.js versions might encounter compatibility problems, unexpected behavior, or silent failures due to changes in core Node.js APIs.
fix Thoroughly test `hock`'s behavior if used with Node.js versions above 10.x. For new projects, prioritize modern, actively maintained HTTP mocking libraries.
npm install hock
yarn add hock
pnpm add hock

This quickstart demonstrates how to set up a `hock` mock server, define expectations for GET and POST requests, send requests to the mock server, and verify that all expectations have been met before shutting down the server.

const http = require('http');
const hock = require('hock');
const request = require('request'); // NOTE: 'request' library is deprecated

const mockPort = 1337;
const mock = hock.createHock();

// Define a mock expectation: a GET request to '/some/url' should return 'Hello!'
mock
    .get('/some/url')
    .reply(200, 'Hello!', { 'Content-Type': 'text/plain' });

mock
    .post('/data', { foo: 'bar' })
    .reply(201, { status: 'created' }, { 'Content-Type': 'application/json' });

// Create an HTTP server that uses hock's handler
const server = http.createServer(mock.handler);

server.listen(mockPort, () => {
    console.log(`Mock server listening on http://localhost:${mockPort}`);

    // Make an HTTP request to the mock server for GET /some/url
    request(`http://localhost:${mockPort}/some/url`, (err, res, body) => {
        if (err) { console.error('GET Request failed:', err); return; }
        console.log(`GET /some/url: Status ${res.statusCode}, Body: ${body}`);
    });

    // Make an HTTP request to the mock server for POST /data
    request.post({
        url: `http://localhost:${mockPort}/data`,
        json: { foo: 'bar' }
    }, (err, res, body) => {
        if (err) { console.error('POST Request failed:', err); return; }
        console.log(`POST /data: Status ${res.statusCode}, Body: ${JSON.stringify(body)}`);

        // Verify all mocks are satisfied and close the server
        if (mock.remainingExpectations === 0) {
            console.log('All mock expectations satisfied.');
        } else {
            console.warn(`${mock.remainingExpectations} mock expectations remain unsatisfied.`);
        }
        server.close(() => { console.log('Mock server closed.'); });
    });
});

server.on('error', (e) => { console.error('Server error:', e); });