HTTPtestify
HTTPtestify is a Node.js library designed for comprehensive integration testing of HTTP APIs. It provides a promise-based API, drawing inspiration from Axios, to facilitate making HTTP requests, asserting response properties, and conducting end-to-end tests. The current stable version is 1.0.3, with releases driven by feature additions and minor bug fixes rather than a strict schedule. Key differentiators include its extensive support for various HTTP methods (GET, POST, PUT, DELETE), advanced request customization (headers, body, query parameters), and sophisticated parallel request handling capabilities like `all`, `race`, and `allSettled`. The library also offers features such as request cancellation, proxy support, robust cookie and session management, and automatic parsing of JSON and optional XML responses, making it a versatile tool for complex API testing scenarios.
Common errors
-
TypeError: HTTPtestify.request is not a function
cause Attempting to destructure `request` as a named import (e.g., `import { request } from 'http-testify'`) when it's a method on the default export.fixImport the default `HTTPtestify` object and then call `HTTPtestify.request(app)`. -
AssertionError: Expected status 200, got 404
cause The tested API endpoint returned an unexpected HTTP status code, often due to an incorrect route, missing handler, or server-side error.fixVerify the endpoint path, HTTP method, and server-side route definitions. Check server logs for internal errors during the request. -
UnhandledPromiseRejectionWarning: This error originated either by throwing an error inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
cause An `http-testify` operation (or subsequent assertion) rejected a Promise, and the rejection was not caught by an `await` within a `try/catch` block or a `.catch()` handler.fixWrap asynchronous test code in `try...catch` blocks, or ensure all Promises are handled with `.catch()` to log or assert on errors explicitly.
Warnings
- gotcha When migrating from older CommonJS (`require`) patterns to modern ESM (`import`) in Node.js, ensure your project's `package.json` and TypeScript configuration are set up for ESM, as `http-testify` ships with types and is designed for modern usage.
- gotcha Asynchronous operations with `http-testify` require proper handling of Promises. Forgetting `await` or neglecting `.then().catch()` chains can lead to tests completing prematurely or unhandled promise rejections, making debugging difficult.
- gotcha While `http-testify` manages the lifecycle of its internal mock server, it's crucial to ensure proper test isolation and cleanup within your test suite. Shared state or external resources not properly reset between tests can lead to flaky results.
Install
-
npm install http-testify -
yarn add http-testify -
pnpm add http-testify
Imports
- HTTPtestify
const HTTPtestify = require('http-testify');import HTTPtestify from 'http-testify';
- request
import { request } from 'http-testify';const server = HTTPtestify.request(app);
- get
HTTPtestify.get('/api/data').then(...);server.get('/api/data').then(...);
Quickstart
import HTTPtestify from 'http-testify';
import express from 'express'; // Common framework for HTTP APIs
// 1. Create a minimal Express app instance for testing
const app = express();
app.use(express.json()); // Enable JSON body parsing for POST requests
// Define a simple GET endpoint
app.get('/api/status', (req, res) => {
res.status(200).json({ status: 'ok', version: '1.0' });
});
// Define a simple POST endpoint
app.post('/api/submit', (req, res) => {
const data = req.body;
res.status(201).json({ message: 'Data received', received: data });
});
// 2. Initialize HTTPtestify with the app instance
const server = HTTPtestify.request(app);
// 3. Define an async test function
async function runExampleTests() {
try {
// Perform a GET request
const getResponse = await server.get('/api/status');
console.log('GET /api/status Status:', getResponse.status); // Expected: 200
console.log('GET /api/status Data:', getResponse.data); // Expected: { status: 'ok', version: '1.0' }
// Perform a POST request with a JSON body
const postResponse = await server.post('/api/submit', { item: 'widget', quantity: 5 });
console.log('POST /api/submit Status:', postResponse.status); // Expected: 201
console.log('POST /api/submit Data:', postResponse.data); // Expected: { message: 'Data received', received: { item: 'widget', quantity: 5 } }
// Demonstrate parallel GET requests
const [res1, res2] = await server.all((instance) => [
instance.get('/api/status'),
instance.get('/api/status')
]);
console.log('Parallel Requests Results:', res1.status, res2.status);
console.log('\nAll example tests completed successfully!');
} catch (error) {
console.error('An error occurred during tests:', error);
}
}
runExampleTests();