Supertest is an HTTP assertion library built on top of SuperAgent, designed for testing web applications and APIs in Node.js. It simplifies making HTTP requests to an application (or a raw http.Server instance) and asserting on the responses. Key features include automatically binding the server to an ephemeral port, chaining assertions for status codes, headers, and body content, and seamless integration with any JavaScript test framework. The current stable version is 7.2.2, with recent releases indicating an active maintenance schedule focused on bug fixes and dependency updates. It provides a high-level abstraction, allowing developers to write clear and concise HTTP tests while retaining the ability to leverage SuperAgent's lower-level API when needed. It is a fundamental tool for integration testing of Node.js web services, especially when using frameworks like Express or Koa.
npm install supertestVerified import paths — ran on the pinned version, not inferred.
Demonstrates making GET and POST requests to an Express application, asserting on response status, headers, and body content using Supertest's fluent API without a formal test runner.
Upgrade your Node.js environment to version 14.16.0 or newer. Ensure your `package.json`'s `engines` field and CI/CD configurations reflect this change.
Always include `.expect(status)` for expected success codes. Additionally, always check for and handle the `err` argument within your `.end()` callback, for example, `if (err) return done(err);` in test frameworks.
Ensure that your `.end()` callback properly handles the `err` argument by either re-throwing it (`if (err) throw err;`) or by passing it to your test framework's `done` callback (`if (err) return done(err);`).
Manually ensure your test server is properly closed after tests. Implement a cleanup hook (e.g., `afterAll` or `afterEach` in Jest/Mocha) that calls `server.close()` on your `http.Server` instance.
Ensure that any `http.Server` instance passed to `request()` is explicitly closed after your tests complete, typically in an `afterEach` or `afterAll` hook of your test runner using `server.close()`.
Verify that the URL path and HTTP method (e.g., `.get('/user')`) exactly match a defined route in your application code. Double-check your application's route definitions and middleware application order.Within your `.end()` callback, ensure you explicitly handle any `err` argument. For example, in Mocha or Jest with `done` callback, use `if (err) return done(err);` or simply `if (err) throw err;` if using promises or async/await.