Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › API testing

How to Test TypeScript Node.js APIs with Vitest and Supertest (Step by Step)

By Freedom251 Team · · 12 min read

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use Vitest to discover, run, and organize your TypeScript test suite, and use Supertest to exercise your Node.js API over HTTP without hard-coding a port. The reliable pattern is to export a configured application from one module, keep listen() in a separate startup file, import the application in tests, await every request, and assert the documented status, content type, and response fields. A useful suite covers successful requests as well as validation, authentication, authorization, missing resources, conflicts, and controlled server failures. Database state, clocks, environment variables, and outbound clients must be isolated so the same test produces the same result locally and in CI.

What do Vitest and Supertest each do?

Vitest is the test runner and expectation layer. It finds test files, executes them, reports failures, and provides functions such as describe, it, and expect. Supertest is the HTTP layer: it sends requests to a Node.js application or HTTP server and lets you assert status codes, headers, and response bodies.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Keeping those jobs separate makes failures easier to interpret. A failing expectation means the API returned an unexpected contract; a Vitest configuration or lifecycle failure means the test did not reach the application as intended. Supertest can accept an application function or server and, when the server is not already listening, bind an ephemeral port for the request. Your tests therefore do not need a shared development port.

How do I install Vitest and Supertest in a TypeScript project?

Install both packages as development dependencies from the project directory:

Popular on Amazon
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
npm install -D vitest supertest

Supertest includes TypeScript declarations in current releases. If your project reports missing types, use the package’s documented type support and keep the dependency version aligned with the rest of the project rather than suppressing the error globally.

Add scripts that distinguish watch mode from a one-shot run:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run"
  }
}

npm test starts Vitest’s interactive mode, which is useful while developing. npm run test:run invokes vitest run, executes the suite once, and exits with a nonzero status when a test fails; that is the appropriate form for CI.

How should TypeScript modules be configured?

Keep the TypeScript module setting consistent with the Node.js runtime and the package’s ESM or CommonJS choice. An ESM project should use ESM-compatible imports and a matching Node runtime; a CommonJS project should use the corresponding compiler and package settings. Mixing the two conventions can make the application import work in development but fail when Vitest loads it.

Do not create a second, test-only module system unless there is a clear reason. The test should import the same application module that production starts, so route registration, middleware order, and serialization are tested as deployed.

How should I structure a Node.js API so Supertest can import it?

Export the fully configured application separately from the file that opens a network listener. The application module should create middleware and register routes; the startup module should call listen(). This separation prevents tests from opening a persistent port and avoids collisions when several test files run together.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Application module

The following Express-shaped example is illustrative. Keep the same separation if your API uses another Node HTTP framework, adapting the export to that framework’s application object or request handler.

// src/app.ts
import express from 'express'

export const app = express()

app.use(express.json())

app.get('/health', (_request, response) => {
  response.status(200).json({ status: 'ok' })
})

export default app

Startup module

// src/server.ts
import app from './app'

const port = Number(process.env.PORT ?? 3000)

app.listen(port, () => {
  console.log(`API listening on ${port}`)
})

The test imports app, not server.ts. Importing the startup file would call listen() during test collection and leave an open handle after the assertion. If your application currently combines route registration and startup, move the listener into a small wrapper before writing HTTP tests.

How do I inject dependencies for repeatable tests?

Pass database clients, queues, clocks, and third-party clients into the application or service constructors instead of reading mutable singletons deep inside route handlers. In a test, provide an in-memory implementation or a fake with controlled responses. This lets you force a dependency failure and verify the API’s error contract without making a real network call.

Also popular on Amazon
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Environment variables deserve the same treatment. Set the values required by the test explicitly, restore changed values in teardown, and do not rely on whichever variables happen to be present in a developer’s shell.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I write my first Vitest and Supertest request?

Import Supertest’s request function, Vitest’s test helpers, and the exported application. Await the request, then assert the externally visible contract.

import request from 'supertest'
import { describe, expect, it } from 'vitest'
import { app } from '../src/app'

describe('GET /health', () => {
  it('returns a health response', async () => {
    const response = await request(app).get('/health')

    expect(response.status).toBe(200)
    expect(response.headers['content-type']).toMatch(/json/)
    expect(response.body).toMatchObject({ status: 'ok' })
  })
})

The route and response shape are examples; replace them with the contract your API documents. The important sequence is request, await, status assertion, content-type assertion where JSON is promised, and a stable body assertion. If the endpoint returns generated IDs or timestamps, assert their type or presence rather than an exact value unless the test controls the generator.

Can I chain Supertest assertions?

Yes. Supertest supports status, header, and body assertions on the request chain, and it also works with a promise or async/await style. Pick one style per test and make sure the test returns or awaits the chain; otherwise Vitest can finish before the HTTP operation has failed.

Which API behaviors should the test suite cover?

Build a behavior matrix from the API contract instead of writing only a happy-path example. Each route should have at least one successful case and the failure cases that clients must handle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Successful requests

Send valid input and verify the documented 2xx status, content type, and response schema. Assert fields that clients depend on, including nested objects and pagination metadata when those are part of the contract. Do not assert incidental property order or implementation-only fields.

Validation failures

Test missing fields, malformed values, and boundary values that the validator rejects. Confirm the documented 4xx status and a machine-readable error shape. If the API returns multiple field errors, assert the fields and codes while avoiding an order-dependent comparison unless ordering is guaranteed.

Authentication failures

Send no credentials and send deliberately invalid credentials as separate cases when the API distinguishes them. Verify that both are rejected consistently and that the response does not expose secrets or internal authentication details.

Authorization failures

Authenticate as a user who lacks the required permission. This is different from missing authentication: the test should prove that middleware recognizes the identity but still denies the protected operation with the documented response.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Missing resources and conflicts

Request an ID that does not exist and verify the API’s not-found contract. Separately, create or submit data that violates a uniqueness rule and assert the documented conflict response. Keeping these cases distinct prevents clients from having to interpret one generic error for two different recovery actions.

Controlled server failures

Configure an injected dependency to throw or return a failure, then call the route. Verify a controlled 5xx response, the promised content type, and an error body suitable for clients. The response must not leak stack traces, credentials, SQL text, or other internals. The test should also prove that the failure is handled rather than leaving the request hanging.

What should I assert in an HTTP-level test?

Assert the stable parts of the public contract: status, content type when promised, and response fields that a client needs. Supertest exposes headers and parsed bodies, so these checks can stay close to the way a real client observes the API.

  • Status: verify the exact documented status for each branch, not merely that it is in the broad 2xx or 4xx range.
  • Headers: check JSON content type for JSON endpoints and any other header explicitly guaranteed by the API.
  • Body: use partial matching for stable fields when the response contains generated values, timestamps, or implementation metadata.
  • Errors: assert machine-readable codes or field names, while avoiding assertions on localized prose unless that wording is part of the contract.
  • Collections: normalize or sort data before comparing it if order is not guaranteed.

Snapshots can hide useful intent when IDs, timestamps, or collection order change frequently. Prefer explicit assertions for contract fields; use a snapshot only after deliberately normalizing volatile values and deciding that the complete serialized shape is itself the contract.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I isolate state and clean up resources?

Repeatability is a design requirement, not a final polishing step. A test that passes only after another test has inserted data is not proving an API behavior.

Database state

Choose one strategy and apply it consistently: reset tables or collections between tests, wrap each test in a transaction that is rolled back, or create isolated fixtures with unique identifiers. Ensure cleanup runs when an assertion fails, not only on the happy path. If tests run concurrently, a shared database must still prevent one test’s writes from changing another’s result.

Timers and clocks

Inject a clock or use the test runner’s controlled timers when business rules depend on time. Restore real timers after each test. Avoid asserting the exact current timestamp unless the clock is fixed; assert ranges or normalized values instead.

Queues, pools, and other handles

Close database pools, queue consumers, timers, and other application-owned resources in teardown hooks. An unclosed handle can make a local run appear to hang and can keep a CI worker alive after all assertions have completed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Outbound HTTP

Keep calls to payment, email, identity, and other external services behind injectable clients. Replace those clients with fakes when testing route and business behavior. Reserve live integration checks for a separately managed environment; a unit or HTTP contract test should not depend on an internet service that can be slow or unavailable.

Also popular on Amazon
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Process-wide state

Do not mutate module-level configuration, environment variables, or singleton caches without restoring them. Avoid tests that depend on execution order. Each test should establish its own inputs and leave the process in a state that the next test can use.

Should I test business logic directly or through HTTP?

Use both layers, with different responsibilities. Direct unit tests are faster and isolate complex rules; a smaller Supertest suite verifies that routing, middleware, serialization, validation, and authentication work together.

Layer What it proves Speed and setup Typical failure signal
Direct unit test Pure business rules, transformations, and edge cases in a service or function Usually fastest with the least infrastructure A specific rule or dependency interaction is wrong
HTTP-level test with Supertest Route selection, middleware order, parsing, status codes, headers, serialization, and integrated authorization More setup and slower than a direct call, but still local and deterministic when dependencies are isolated The public API contract or request pipeline is wrong

Do not duplicate every business-rule case at the HTTP layer. Keep exhaustive combinations in unit tests and retain representative HTTP cases for each route branch and middleware boundary. When an HTTP test fails, a focused unit test can then identify whether the defect is in business logic or in request handling.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I run Vitest reliably in CI?

Use the one-shot command and make the process exit status control the job:

npm ci
npm run test:run

vitest run is the non-watch invocation documented for CI. The job should fail when Vitest reports a failed test, so do not append shell operators that mask a nonzero exit code.

What should be pinned?

Pin the Node.js runtime and package-manager versions used by the project, and commit the lockfile. Install from that lockfile in CI so Vitest, Supertest, TypeScript, and transitive dependencies are resolved consistently. Before publishing a setup command, check the package versions and Node.js compatibility required by the versions your project has selected; those requirements change over time.

How should CI provide configuration?

Set required environment variables explicitly in the CI job or its secret store. Use a test database or isolated schema, deterministic service endpoints, and the same module mode as local development. Never print credentials or full environment dumps in failure logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I add coverage or JUnit output immediately?

Add reporting only after the basic suite is stable and you have checked the current Vitest command-line options for the versions you installed. Coverage thresholds and JUnit files are useful when a project has a defined consumer for them, but an unverified flag can make a correct test suite fail before tests start. Provider-specific YAML is a project decision; keep the portable part in the npm script and configure provider syntax around it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What are the most common Vitest and Supertest failures?

“Address already in use” or tests that never exit

Check whether a test imports the startup module instead of the exported application. Move listen() back to the process entry point, close pools and timers in teardown, and let Supertest create its ephemeral listener.

Also popular on Amazon
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

“Cannot use import statement” or module-resolution errors

Align TypeScript, package, Vitest, and Node settings around one ESM or CommonJS strategy. Check the package’s module type, compiler output, and the way test files import the application. Avoid fixing one file with an incompatible transpilation override that leaves the rest of the project inconsistent.

The request succeeds but the body is empty

Confirm that the route’s body parser is registered before the route and that the test sends the input in the format the endpoint expects. For JSON, send a JSON payload through Supertest and assert the response content type separately from the body shape.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tests pass alone but fail as a suite

Look for shared database rows, mutable module state, leaked environment variables, fake timers that were not restored, and outbound calls that retain state. Run cleanup in hooks that execute after failures and give concurrent tests isolated fixtures.

An assertion is flaky

Identify volatile IDs, timestamps, random ordering, and real external calls. Control the generator or clock, normalize collections, and replace the external client with a deterministic fake. Assert the API’s stable contract instead of an incidental representation.

How can I expand the example into a maintainable API test suite?

Start with one representative route, then repeat a deliberate pattern for every endpoint:

  1. Write the documented request and response contract, including success and failure statuses.
  2. Create fixtures or fakes for the database and outbound dependencies.
  3. Test the successful response with status, content type, and stable fields.
  4. Add validation, authentication, authorization, not-found, conflict, and dependency-failure cases that apply to the route.
  5. Reset state and restore timers, environment variables, and mocks after each test.
  6. Run the same one-shot command locally and in CI.

Keep test descriptions specific enough to identify the violated behavior, such as “rejects a request without the required permission” rather than “route works.” Group related cases with describe, but do not make the grouping imply an execution order. A well-named test suite becomes an executable map of the API contract and a fast diagnostic when a change breaks clients.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I use a real TCP port for API tests?

You can, but it adds lifecycle and collision problems that are unnecessary for most route tests. Passing the application or an unstarted server to Supertest lets it bind an ephemeral port, so parallel test processes do not need a shared port reservation.

How do I test an endpoint that streams or returns binary data?

Treat the payload format as part of that endpoint’s contract and assert the relevant content type, status, and byte-level or length properties. Do not force a JSON body matcher onto a response that is intentionally not JSON; keep binary comparisons deterministic by using a fixed fixture.

What belongs in an end-to-end environment instead of a Supertest test?

Use a separate environment when the behavior depends on real infrastructure whose configuration is itself under test, such as a deployed gateway, managed database, or external identity provider. Keep the local Supertest suite focused on the application pipeline with controlled dependencies so ordinary failures remain fast and diagnosable.

How should I handle API versioned routes in the test files?

Organize tests around the public versioned path and keep fixtures specific to that version’s schema. When a new version intentionally changes status codes or fields, add a separate contract group rather than weakening assertions for the existing version.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

API testingautomated testingCINode.jsSuperTestTypeScriptVitest

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.