New
Apps 6,419Makers 6,403This week 7
Promote your app−30%
3views in
the last 30 days
spectest logo

Spectest

declarative API testing CLI for fast HTTP endpoint tests


Spectest is a lightweight API testing CLI for writing declarative HTTP endpoint tests in JavaScript, JSON, or YAML. Use it to verify REST APIs, assert status codes, headers, JSON payloads, and schemas, test multi-step API flows, replay recorded outbound HTTP calls, and run concurrency or load checks without a browser automation framework.

Features

  • Declarative API tests: describe requests and expected responses with a simple *.spectest.* file.
  • HTTP assertions: validate status codes, response headers, partial JSON bodies, and Zod or JSON schemas.
  • OpenAPI loading: run OpenAPI 3.0/3.1 operations directly with --openapi.
  • API flow testing: chain login, setup, teardown, and dependent requests with shared response state.
  • Record and replay: capture outbound fetch, http, https, and common Node library calls into reusable cassettes.
  • CLI-first workflow: run tests with npx spectest, filter by tags or names, randomize ordering, and snapshot failures.
  • Concurrency and load checks: send tests in parallel, rate-limit requests, or bombard endpoints to check API robustness.

Getting Started

A spectest is a collection of test cases. The only required properties of a test case are

  • name - used to identify the case
  • endpoint - the API endpoint under test.

Most test cases include a request property which mirrors the fetch Request schema, and a response property that is used for assertions. The response property also mirrors the fetch Response schema.

1. Define the server environment

At the root of your project, create the file spectest.config.js. For the purposes of this guide, we'll be using https://jsonplaceholder.typicode.com, which provides "free fake and reliable API for testing and prototyping".

// spectest.config.js

export default {
  baseUrl: 'https://jsonplaceholder.typicode.com',
  testDir: './test',
  filePattern: '\\.spectest\\.',
};

For actual testing, the baseUrl should be the hostname of your server like http://localhost:3000 for Express servers. The CLI would search for and process files that match filePattern under the testDir. For more config options, see Config reference.

2. Create some spec test cases

Create the file test/jsonpayload.spectest.js and paste the code below in it. Note: the file name needs to match the pattern defined in the config above.

// jsonpayload.spectest.js

const tests = [
  // This basic example fetches {baseUrl}/todos/1 and asserts response status is 'OK'.
  {
    name: "Fetch TODO 1",
    endpoint: "/todos/1",
  },

  // In this case, spectest would assert the actual response matches both status code and json body. 
  {
    name: "Create a post",
    endpoint: "/posts",
    request: {
      method: "POST",
      headers: { "Content-Type": "application/json; charset=UTF-8" },
      body: { title: "foo", body: "bar", userId: 1 },
    },
    response: {
      status: 201,
      json: { id: 101, title: "foo", body: "bar", userId: 1 },
    },
  },
];

export default tests;

A *.spectest.js file can have classes, functions, use imports and do anything you would with Javascript. The default export may be either an array of test cases or an object with a tests array and optional name property. For the full schema of a test case, see Testcase reference

3. Run the test cases

You can run the test cases with:

$ npx spectest

# Run the cases in a specific file
$ npx spectest jsonpayload.spectest.js

# Set/override the configs in step 1
$ npx spectest --base-url="https://jsonplaceholder.typicode.com" jsonpayload.spectest.js

All three commands above will have the same output, and it would look like:

📊 Test Summary:
 [✅] Fetch TODO 1 (53ms)
 [✅] Create a post (108ms)

✅ 2/2 tests passed!
📋 Server logs captured: 0
⏱️ Latency: min 53ms; avg 80ms; max 108ms
⏱️ Testing time: 0.11s; Total time: 0.18s

Running OpenAPI documents

Spectest can load OpenAPI 3.0 and 3.1 documents directly:

npx spectest --openapi ./examples/openapi/jsonplaceholder.yaml --base-url=https://jsonplaceholder.typicode.com

Generated tests stay in memory; Spectest does not write .spectest files for this workflow (see spectest generate openapi-tests below if you want a written scaffold instead). Spectest uses examples or schema defaults for required path/query/header/cookie parameters and required JSON request bodies. Operations that need missing values, unsupported media types, unsupported parameter serialization, unresolved external refs, unsupported schema constructs, or unavailable auth/hook lookups are generated as skipped tests with skip reasons.

When both --openapi and testDir are configured, Spectest loads OpenAPI-generated tests and hand-written suites into the same run and dependency graph — a hand-written suite can dependsOn a spec-generated operationId, and duplicate operationIds across the two sources fail fast via the same uniqueness check.

Multiple examples per operation

If a request body, parameter, or response defines an examples map (rather than a single example), Spectest generates one test per entry. Each generated test's operationId becomes ${operationId}+${exampleKey} and its name gets a — ${exampleKey} suffix.

The expected response for a given request example is resolved in order:

  1. x-spectest.status declared on that example.
  2. A response example under a documented non-2xx status sharing the same key as the request example.
  3. The lowest documented 2xx status (the v1 default).

An operation with no examples map behaves exactly as before (a single generated test, unsuffixed operationId).

x-spectest vendor extension

A single vendor extension, allowed on an operation and on an individual entry inside an examples map (example-level overrides operation-level):

x-spectest:
  status: 400
  tags: [slow, real-backend]
  skip: true
  skipReason: "hits real registrar, run manually"
  phase: setup | main | teardown
  dependsOn: [operationId, "otherOperationId+exampleKey"]
  beforeSend: hookName        # looked up in cfg.openapiHooks
  postTest: hookName
  security: none | variantName
  generate:                   # dynamic values, see below
    orderId: uuid
    "product.domainName": shortId

Named hook registry

Add openapiHooks to spectest.config.js to give x-spectest.beforeSend/postTest something to resolve against:

export default {
  openapiHooks: {
    extractOneTimeToken: {
      postTest: async (res, state, ctx) => { /* scrape ctx.logs, stash in state */ },
    },
  },
};

A name referenced by x-spectest that isn't in openapiHooks generates a skipped test with a reason, the same way a missing openapiAuth hook does — it never crashes the loader.

Dynamic example values

Use {{uuid}}, {{timestamp}}, or {{shortId}} as a literal example string to get a fresh value resolved once per generated test (stable across repeat/bombard reruns of that same test). For object bodies, x-spectest.generate is the path-keyed alternative — list which fields need freshness per run instead of rewriting the example. Both are opt-in; Spectest still never synthesizes data for a property that has no example.

Explicit non-default auth cases

openapiAuth entries can be either a single hook (as in v1) or a named-variant map, to let you deliberately generate a test with missing/expired credentials:

export default {
  openapiAuth: {
    session: {
      valid: async (ctx) => ({ headers: { Cookie: 'session=...' } }),
      expired: async (ctx) => ({ headers: { Cookie: 'session=expired' } }),
      missing: async () => ({}),
    },
  },
};

Set x-spectest.security: none to bypass security application entirely for an example, or x-spectest.security: expired (etc.) to pick a variant. With no override, a variant map defaults to its valid entry.

Native links for chaining

Standard OpenAPI responses.<status>.links are honored for simple data-passing chains (e.g. register something, then fetch it using the orderId from the first response). When operation B has an unresolved parameter or request body and an earlier operation A declares a link targeting B by operationId, Spectest auto-generates dependsOn: [A] plus a beforeSend that reads the linked value from state.completedCases[A] via the link's runtime expression ($response.body#/pointer or $response.header.<name>). This only applies when A itself resolves to exactly one generated test; if A was split by multiple examples, use x-spectest.dependsOn + beforeSend/hooks instead.

Schema-driven negative testing

Beyond example-based negative cases (a 400 response paired with a hand-written invalid example), Spectest can derive negative cases directly from an operation's JSON Schema constraints — mutating one field of an existing example at a time (drop a required field, violate minLength/maximum/enum/pattern/format/additionalProperties, etc.) and asserting the documented 4xx response. This is opt-in and off by default; every mutation starts from a real hand-written example, so Spectest still never invents data for a field that has no example.

npx spectest --openapi ./openapi.yaml --negative-tests
// spectest.config.js
export default {
  openapiNegativeTests: {
    enabled: true,
    maxCasesPerOperation: 20,       // cap per operation
    excludeTags: ['real-backend'],  // operations with this tag/x-spectest.tags entry are never mutated
  },
};

Generated cases are tagged negative (alongside openapi), so --tags/--filter can include or exclude them like any other test. Per-operation, x-spectest.negative can narrow (but not force-enable when the global flag is off):

x-spectest:
  negative:
    enabled: false        # opt this operation out entirely
    fields: [email, age]  # restrict mutation to specific top-level body/query/cookie fields
    status: 422            # pin the expected status instead of the lowest documented 4xx
    seedExample: default   # which existing example key to mutate from (default: first key in spec order)

Negative generation is skipped (no crash, no cases) for an operation when: no hand-written example exists to seed from; the operation or its native tags/x-spectest.tags match excludeTags; the operation declares x-spectest.dependsOn or participates in a links chain (mutating a chain link risks breaking dependents that rely on its real response); or no documented 4xx response exists to assert against. Only request body and query/cookie parameters are mutated — path and header parameters are excluded since an invalid value there is often rejected by the HTTP client or the router before it reaches your handler, making the expected status ambiguous.

Contract coverage reporting

npx spectest --openapi ./openapi.yaml --coverage-report
npx spectest --openapi ./openapi.yaml --coverage-report --coverage-report-file ./coverage.txt

After the run, prints one line per spec operation: generated & passed, generated & failed, generated & skipped (<reason>), covered by hand-written test <operationId> (when a hand-written suite's request matches that operation's method/path but no generated test ran for it), or uncovered. When negative testing generated cases for an operation, the line gets a (+N negative) suffix.

Scaffolding editable test files

npx spectest generate openapi-tests --openapi ./openapi.yaml --output ./test

Writes a .spectest.js file with the same generated tests Spectest would run in-memory, as an editable starting point for suites that will grow real beforeSend/postTest logic by hand. Anything expressible this way is already expressible via direct --openapi loading — this is a convenience/onboarding command, not a coverage unlock.

Why Spectest

While building an API, I kept running into the same frustrating loop: after writing comprehensive Jest tests, I still had to manually “verify” the API by running it through a frontend client.

Here’s why Jest alone wasn’t enough:

  1. Mocks obscure reality – Jest enables mocking which simulate behavior but can hide real issues in production.

  2. Multi-step flows were painful – Chaining flows like login → verify → fetch was hard to write and even harder to maintain.

  3. No browser-like behavior – Jest couldn’t replicate real-world HTTP behavior like cookie persistence or automatic attachment.

  4. API-centric needs were missing – Load testing, proxying, and concurrency checks weren’t feasible out of the box.

What I really needed was a way to verify my API contract the same way a frontend does—but without reaching for heavyweight tools like Selenium or Playwright.

That’s where Spectest was born—out of necessity.

API Reference

Test case options

Option Description Default
name Human readable test name required
operationId Unique identifier for the operation name
phase Execution phase of the test (setup, main, or teardown) main
dependsOn Array of operationId strings that must pass before this test runs none
endpoint Request path relative to the base URL required
request.method HTTP method GET
request.headers Additional request headers none
request.body Request payload none
request.* Other valid fetch Request option keys, e.g. cache, mode. none
response.status Expected HTTP status 200
response.json Expected partial JSON body none
response.schema Zod or JSON schema for response none
response.headers Expected response headers none
response.* Other valid fetch Response response keys e.g. statusText, type. none
beforeSend Function used to finalize the request none
postTest Function used to process response, usually to extract and save data. none
tags Tags used for filtering none
skip Skip the test case false
focus Run only focused tests when present false
repeat Extra sequential runs of the test 0
bombard Additional simultaneous runs of the test 0
delay Milliseconds to wait before running none
timeout Per-test timeout override runtime timeout (60000ms)
recording Per-test HTTP recording mode override (off, replay, or record) runtime recording

Config options

Option Description Default
configFile Path to an extra config file none
baseUrl Base URL of the API http://localhost:3000
testDir Directory containing test suites ./test
filePattern Regex for suite filenames \.spectest\.
startCmd Command to start the test server npm run start
buildCmd Command to build the test server none
runningServer Handling for an existing server (reuse, fail, or kill) reuse
serverStartupTimeout Max time (ms) to wait for a spawned server to become ready before failing 30000
serverHealthCheckInterval Interval (ms) between server readiness health check attempts 250
tags String list used for filtering tests []
rps Requests per second rate limit Infinity
timeout Default request timeout in milliseconds 60000
snapshotFile Path to write a snapshot file none
randomize Shuffle tests ordering before execution false
happy Run only tests expecting 2xx status. Quick filter for testing the happy path. false
filter Regex or smart filter to select tests (happy, failures) none
testOutput Executed test result detail (summary or errors). Use errors to include failed-test server logs and failure reasons in the report. summary
verbose Verbose spectest runner/program output. This is separate from test result detail. false
userAgent Browser User-Agent string to send or one of the predefined user-agents. chrome_windows
recording HTTP recording mode for outbound Node SUT requests (off, replay, or record) off
recordingFile JSON cassette path used for HTTP recordings .spectest/cassette.json
missingRecordingBehavior Behavior when replay cannot find a cassette entry (fail, record, or bypass) fail
recordingExcludeUrls URL patterns that always bypass HTTP cassette handling []
outboundThrottle Rate limit rules capping outbound requests the Node SUT process makes to matching backends []
openapi Path to an OpenAPI 3.0/3.1 document to load directly none
openapiServer Server URL or index to select when an OpenAPI document has multiple servers entries none
openapiAuth Map of OpenAPI security scheme names to request mutation hooks, or to a named-variant map ({ valid, expired, ... }) {}
openapiHooks Map of hook names to { beforeSend?, postTest? }, resolved by x-spectest.beforeSend/postTest {}
coverageReport (--coverage-report) Print an OpenAPI contract coverage report after the run false
coverageReportFile (--coverage-report-file) Write the coverage report to a file instead of stdout none
openapiNegativeTests (--negative-tests toggles .enabled) { enabled, maxCasesPerOperation, excludeTags } for schema-derived negative test generation { enabled: false, maxCasesPerOperation: 20, excludeTags: ['real-backend'] }
suiteFile Run only the specified suite file none
projectRoot (--dir) Root directory of the project current working directory

testOutput can also be set from the CLI with --test-output=summary or --test-output=errors. HTTP recording can be set with --recording=off|replay|record, --recording-file=<path>, and --missing-recording-behavior=fail|record|bypass. CLI values override spectest.config.js.

API Testing Tips

Setup and Teardown

For tests that need to run before all others (e.g., checking server status) or after all others (e.g., logging out), you can use the phase property. The phase can be set to setup, main (default), or teardown.

This is syntactic sugar for dependsOn, ensuring that setup tests block main and teardown tests, and main tests block teardown tests.

export default [
  {
    name: 'Ping Server',
    endpoint: '/ping',
    response: { status: 200 },
    phase: 'setup',
  },
  {
    name: 'Main Test',
    endpoint: '/some-data',
    response: { status: 200 },
  },
  {
    name: 'Logout',
    endpoint: '/logout',
    response: { status: 200 },
    phase: 'teardown',
  },
];

Alternatively, you can structure your suite with setup, tests, and teardown properties:

export default {
  name: 'My Suite',
  setup: [
    {
      name: 'Ping Server',
      endpoint: '/ping',
      response: { status: 200 },
    },
  ],
  tests: [
    {
      name: 'Main Test',
      endpoint: '/some-data',
      response: { status: 200 },
    },
  ],
  teardown: [
    {
      name: 'Logout',
      endpoint: '/logout',
    

Description taken from the repository README.

Ratings

–
0 ratings
5 0
4 0
3 0
2 0
1 0

Rate this app

Sign in to rate

Comments 0

Sign in to comment

No comments yet.

Related apps

#api-testing · #testing · #dev-tools