Skip to content

API_AUTWrapper

Mat Walker edited this page Nov 26, 2026 · 1 revision
import { API_AUTWrapper } from '@controlium/framework';

Wraps one HTTP target for API-level testing. Two kinds, one class:

  • AUT — a service this process starts, calls, and stops (startNewApplication, or prepareApplication + startApplication).
  • API — a service already running elsewhere; this process only calls it, never starts or stops it (registerAPI, or prepareAPI).

Any number of instances, of either kind, run at once. Each has a unique appName and sits in one shared registry.

Start an AUT directly

let api: API_AUTWrapper<INestApplication>;

api = await API_AUTWrapper.startNewApplication({
  appName: 'MyAPI',
  port: 3000,
  bootstrapper: async (port) => {
    const app = await NestFactory.create(AppModule);
    await app.listen(port);
    return app;
  },
  closeHandler:  (app) => app.close(),
  getUrlHandler: (app) => app.getUrl(),
});

bootstrapper starts the AUT and returns a handle of any shape. closeHandler closes it. getUrlHandler returns its URL — optional; omit it and resolveURL/isLive build protocol://host:port instead.

Required: port, bootstrapper, closeHandler. Optional: appName (default 'AUT'), getUrlHandler, host (must be 'localhost'), protocol ('http'/'https', default 'http'), requestTimeout (default 30000), proxy, autHandlerTimeout (default 30000).

Start an AUT from settings

Splits config resolution from the actual start, so starting is its own explicit, logged step:

// once, e.g. in Before
API_AUTWrapper.prepareApplication('MyAPI', {
  bootstrapper: async (port) => { /* ... */ },
  closeHandler: (app) => app.close(),
});

// later, e.g. in a step
await API_AUTWrapper.startApplication('MyAPI');

// teardown
await API_AUTWrapper.stopApplication('MyAPI');

prepareApplication resolves host/port/protocol/requestTimeout/proxy/ autHandlerTimeout/resourcePathPreamble from settings under $.testAUTs.<appName>.* (CONTROLIUM_AUT_SETTINGS_PREFIX/autSettingsPrefix to change the testAUTs prefix). See SettingsRegistry for how settings resolve. stopApplication closes the AUT but keeps it registered, so startApplication can restart it by name without re-preparing it.

Connect to an already-running API

const api = API_AUTWrapper.registerAPI({
  appName: 'PaymentsAPI',
  port: 4000,
  host: 'staging.internal',
});

Or resolve connection details from settings under $.testAPIs.<appName>.* (CONTROLIUM_API_SETTINGS_PREFIX/apiSettingsPrefix to change the testAPIs prefix):

const api = API_AUTWrapper.prepareAPI('PaymentsAPI');

No bootstrapper/closeHandler/getUrlHandler — this process never starts or stops an API.

Find a registered instance by name

API_AUTWrapper.getApplication('MyAPI');               // by name
API_AUTWrapper.getApplication();                       // the only one registered
API_AUTWrapper.findAUTOrAPIByTargetText('[MyAPI]');     // accepts 'AUT' | 'API' | '[name]'

Session configuration

await api.setHeaders({ Authorization: `Bearer ${token}` });  // replace
await api.mergeHeaders({ 'X-Trace-Id': id });                 // merge
api.clearHeaders();
api.getHeaders();

await api.setQueryParams({ page: '1' });
await api.mergeQueryParams({ limit: '50' });
api.clearQueryParams();
api.getQueryParams();

api.resourcePathPreamble = '/api/v1';
api.switchResourcePathPreamble('V2');  // picks from $.testAUTs.<appName>.resourcePathPreambles

Set a header/query-param value to null to omit it from requests without removing it from the session set. Set it to the string "_undefined" to remove the key entirely, or "_null" to force a real null value.

Make a request

await api.request('GET', '/users/42');

await api.request('POST', '/users', {
  body: { name: 'Ann' },
  headers: { 'X-Trace-Id': id },       // merged on top of session headers
  queryString: 'dryRun=true',           // combined with session query params
  requestTimeout: 5000,                 // overrides session requestTimeout for this call
  followRedirects: true,                // follow 3xx responses (default: false)
});

request() never throws on a non-responding AUT/API — check api.lastTransaction.error, or api.lastResponse (which throws if there's no response), instead.

Content-Type is set automatically only when the body is a JSON object/string and no Content-Type header is already set. Pass contentType explicitly for anything else (XML, YAML, binary) — a Buffer body is sent byte-exact and never sniffed.

Read back results

api.transactions;      // every request/response (or request/error) this session
api.lastTransaction;   // most recent — throws if none yet
api.lastResponse;       // most recent response — throws if none, or if the target didn't respond
api.clearTransactions();

Following redirects (followRedirects: true) records one transaction per hop; lastTransaction/lastResponse resolve to the final hop.

One-shot overrides (next request only, any AUT/API)

API_AUTWrapper.setNextRequestHeaders({ Authorization: null });     // replaces, one call
API_AUTWrapper.mergeNextRequestHeaders({ 'X-Debug': '1' });         // merges, one call
API_AUTWrapper.setNextRequestQueryParams({ page: '2' });
API_AUTWrapper.mergeNextRequestQueryParams({ limit: '10' });
API_AUTWrapper.clearNextRequestHeaders();
API_AUTWrapper.clearNextRequestQueryParams();

Consumed by whichever request() call fires next across the whole suite — not scoped to one instance.

Liveness and URL

await api.isLive();      // true/false — probes the handler, or the port directly
await api.resolveURL();  // the AUT's/API's URL
api.isSelfManaged;        // true only if this process started it and hasn't closed it since
api.targetKind;            // 'aut' | 'api'

Close

await api.close();                            // this instance only
await API_AUTWrapper.closeAllAUTsAndAPIs();    // every registered instance

close() resets headers, query params, transactions, and the resource-path preamble, but keeps configuration (host/port/protocol/handlers), so the instance can restart. closeAllAUTsAndAPIs() runs automatically in LifecycleHooks.afterTest — see LifecycleHooks.