Registry / testing / specmatic

specmatic

JSON →
library2.41.1jsnpmunverified

Specmatic-node is an npm package that provides a Node.js wrapper for the core Specmatic executable JAR, enabling contract-driven development (CDD) workflows within JavaScript and TypeScript projects. It allows developers to easily install and manage the Specmatic JAR, run CLI commands, and programmatically interact with Specmatic's capabilities for API stubbing (smart mocks) and contract testing. The current stable version is 2.43.3. New patch and minor versions are released frequently, often several times a month, reflecting active development. Its key differentiators include enabling a 'no-code' approach to contract testing from OpenAPI/Swagger/AsyncAPI specifications and providing a smart stub server that can be configured programmatically to simulate API providers, facilitating independent development for API consumers. It bridges the JVM-based core Specmatic functionality with the Node.js ecosystem.

npm install specmatic
INSTALL
IMPORT
SIG · SPECMATIC
S
specmatic
testingjavascriptv2.41.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

startHttpStub
import { startHttpStub } from 'specmatic'
const { startHttpStub } = require('specmatic')
Specmatic primarily uses named exports. Prefer ESM imports in modern Node.js environments.
test
import { test } from 'specmatic'
import test from 'specmatic'
The `test` function for running contract tests is a named export, not a default export.
setHttpStubExpectationJson
import { setHttpStubExpectationJson } from 'specmatic'
const setHttpStubExpectationJson = require('specmatic').setHttpStubExpectationJson
Use named imports for direct access to functions like `setHttpStubExpectationJson`.

Demonstrates how to programmatically start a Specmatic stub server, define and set dynamic expectations, simulate client interaction with the stub, run contract tests against it, and ensure the stub is properly shut down.

import { startHttpStub, setHttpStubExpectationJson, test, stopHttpStub } from 'specmatic'; import path from 'path'; // For resolving specmatic directory // Define the directory where your Specmatic OpenAPI/contract specification files are located. // For example, if your specs are in 'src/specmatic', use path.resolve(__dirname, 'src', 'specmatic') const specmaticDir = path.resolve(__dirname, 'specmatic'); // Adjust this path as needed async function runSpecmaticWorkflow() { let stub; try { console.log(`Attempting to start Specmatic Stub server with specs from: ${specmaticDir}`); // Start the Specmatic stub server, binding it to localhost:9000 // The specmaticDir is passed as an argument to load contract specifications. stub = await startHttpStub('localhost', 9000, [specmaticDir]); console.log(`Specmatic Stub running successfully on ${stub.url} (Process ID: ${stub.pid})`); // Define and set a programmatic expectation for a GET /greeting endpoint on the stub. // This allows the stub to respond with a specific JSON body for a matching request. const expectation = { "method": "GET", "path": "/greeting", "response": { "status": 200, "headers": { "Content-Type": "application/json" }, "body": {"message": "Hello from Specmatic Stub!"} } }; await setHttpStubExpectationJson(expectation, `http://localhost:${stub.port}`); console.log('Stub expectation set for GET /greeting.'); // Simulate an API client interaction by fetching from the stub. // In a real scenario, your application's HTTP client would call this. console.log('Fetching from stub: GET /greeting'); const stubResponse = await fetch(`http://localhost:${stub.port}/greeting`); const stubData = await stubResponse.json(); console.log('Received response from stub:', stubData); // Run contract tests. This typically involves Specmatic verifying your API // implementation against its OpenAPI specifications. For this example, // we are testing against the running stub itself, which should pass if the spec is valid. console.log(`Running contract tests against ${stub.url}`); const testResult = await test(`http://localhost:${stub.port}`, [specmaticDir]); console.log('Contract Test Results:', JSON.stringify(testResult, null, 2)); } catch (error) { console.error('Specmatic workflow failed:', error); process.exit(1); } finally { // Crucially, stop the Specmatic stub server to release resources and terminate the JAR process. if (stub && stub.pid) { console.log(`Stopping Specmatic Stub server (PID: ${stub.pid})...`); await stopHttpStub(stub.pid); console.log('Specmatic Stub stopped.'); } } } // Execute the Specmatic workflow runSpecmaticWorkflow();
specmatic --version
Debug
Known issues
gotchaNode.js versions 17/18 (and potentially others) may experience 'Connection Refused' errors when the Specmatic stub starts, often due to Node's default preference for IPv6 DNS resolution.
fix
Set the environment variable `NODE_OPTIONS=--dns-result-order=ipv4first` before running your Node.js application, or consistently use `localhost` instead of `127.0.0.1` when specifying hostnames for Specmatic.
affects: >=2.x
gotchaThe error 'ReferenceError: setImmediate is not defined' can occur when `specmatic-node` is run in certain environments that lack Node.js global APIs, such as some browser-like test runners or older Node.js versions.
fix
Ensure your execution environment is a Node.js context that provides `setImmediate` or include a polyfill for `setImmediate` if running in a non-standard Node.js setup (e.g., using `jest-environment-jsdom` without appropriate Node.js shims).
affects: >=2.x
gotchaThe Specmatic stub (the underlying Java process) may not terminate automatically after test execution, leading to orphaned processes and potential port conflicts.
fix
Always call `stopHttpStub(stub.pid)` explicitly in your test teardown logic (e.g., `afterAll` hook in Jest) to ensure the Specmatic JAR process is cleanly shut down.
affects: >=2.x
Errors
Common errors & fixes
Connection Refused error when connecting to stub
Node.js DNS resolution order preferring IPv6 on some systems, causing issues when Specmatic binds to IPv4.
fix
Set `NODE_OPTIONS=--dns-result-order=ipv4first` in your shell or use `localhost` consistently instead of `127.0.0.1`.
ReferenceError: setImmediate is not defined
Execution environment lacks the Node.js global `setImmediate` function, often in browser-mocking test setups.
fix
Ensure a standard Node.js test environment is used, or polyfill `setImmediate` for compatibility.
Upgrade
Version history
2.41.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
26 hits · last 30 days
node
22
OpenAI (training)
1
Resources