Skip to main content

Authoring extensions

Recipes from the examples' extensions/, one per kind of extension:

examples/extensions/index.ts
/**
* Example TypeScript WireMock extensions, explained in the guide for extension authors.
*
* | Extension | Kind | Registers |
* |----------------------------|---------------------------------------|------------------------------|
* | `UppercaseTransformer` | Response transformer | class name + JAR |
* | `BodyLengthMatcher` | Custom request matcher | class name + JAR |
* | `StubCountAdminApi` | Admin API extension | class name + JAR |
* | `PoweredByTransformer` | Global transformer, found by scanning | JAR only |
* | `GlobalResponseTemplating` | WireMock's built-in templating | options only, configurable |
*
* @see https://hella-web3.github.io/wiremock-testcontainers-nodejs/docs/extensions/authoring-extensions
*/
export { BodyLengthMatcher, type BodyLengthParameters } from "./body-length-matcher";
export { GlobalResponseTemplating, type GlobalResponseTemplatingOptions } from "./global-response-templating";
export { JavaExtension, type JavaExtensionDefinition } from "./java-extension";
export { JARS, JAVA_PACKAGE } from "./jars";
export { PoweredByTransformer } from "./powered-by-transformer";
export { EXTENSION_CLASSES, PAYMENTS_EXTENSIONS } from "./registry";
export { type AdminApi, StubCountAdminApi } from "./stub-count-admin-api";
export type { CustomMatcherFields, TransformerFields } from "./stubs";
export { UppercaseTransformer, type UppercaseParameters } from "./uppercase-transformer";

Source: examples/extensions/index.ts

Wrap a Java class​

A base class turns name, class and JAR into one super() call:

examples/extensions/java-extension.ts
/**
* Base class for TypeScript extensions that wrap one Java class: a subclass passes its
* {@link JavaExtensionDefinition} to `super()` and adds typed helpers for its stubs.
* @example
* ```typescript
* export class MyTransformer extends JavaExtension {
* constructor() {
* super({ name: "my-transformer", className: "com.acme.MyTransformer", jar: "./acme.jar" });
* }
* }
* ```
*/
export abstract class JavaExtension implements WireMockExtension {
readonly #definition: JavaExtensionDefinition;

protected constructor(definition: JavaExtensionDefinition) {
this.#definition = definition;
}

getName(): string {
return this.#definition.name;
}

getClassNames(): string[] {
return [this.#definition.className];
}

getJars(): WiremockExtensionJar[] {
return [this.#definition.jar];
}
}

Source: examples/extensions/java-extension.ts (lines 19–49)

examples/extensions/uppercase-transformer.ts
/**
* Response transformer (https://wiremock.org/docs/extensibility/transforming-responses/): a stub
* that opts in gets an upper-cased body, an optional suffix and `X-Transformed-By: uppercase`.
*/
export class UppercaseTransformer extends JavaExtension {
/** WireMock's name for it – what stubs list in `transformers`. */
static readonly NAME = "uppercase";
/** The response header it adds. */
static readonly HEADER = "X-Transformed-By";

constructor() {
super({ name: UppercaseTransformer.NAME, className: `${JAVA_PACKAGE}.UppercaseTransformer`, jar: JARS.examples });
}

Source: examples/extensions/uppercase-transformer.ts (lines 17–29)

Keep WireMock's name in static readonly NAME, and expose what tests assert on, like HEADER.

Add typed stub helpers​

Type the fields stubs apply extensions with:

examples/extensions/stubs.ts
/** Added to a stub's `response`: the transformers to run and their parameters. */
export interface TransformerFields<Parameters extends object = object> {
readonly transformers: readonly string[];
readonly transformerParameters?: Parameters;
}

/** Added to a stub's `request`: a custom matcher and its parameters. */
export interface CustomMatcherFields<Parameters extends object = object> {
readonly customMatcher: { readonly name: string; readonly parameters: Parameters };
}

Source: examples/extensions/stubs.ts (lines 9–18)

Return them from static helpers – validating parameters, so mistakes fail where they are written:

examples/extensions/uppercase-transformer.ts
/**
* `response` fields applying the transformer.
* @example response: { status: 200, body: "ok", ...UppercaseTransformer.transform({ suffix: "!" }) }
*/
static transform(parameters: UppercaseParameters = {}): TransformerFields<UppercaseParameters> {
return {
transformers: [UppercaseTransformer.NAME],
...(parameters.suffix === undefined ? {} : { transformerParameters: { suffix: parameters.suffix } }),
};
}

Source: examples/extensions/uppercase-transformer.ts (lines 33–42)

examples/extensions/body-length-matcher.ts
/**
* `request` fields matching bodies longer than `maxLength` bytes.
* @example request: { method: "POST", url: "/notes", ...BodyLengthMatcher.longerThan(20) }
* @throws If `maxLength` is not a non-negative integer – WireMock would fail every match.
*/
static longerThan(maxLength: number): CustomMatcherFields<BodyLengthParameters> {
if (!Number.isInteger(maxLength) || maxLength < 0) {
throw new RangeError(`maxLength must be a non-negative integer, got ${maxLength}`);
}
return { customMatcher: { name: BodyLengthMatcher.NAME, parameters: { maxLength } } };
}

Source: examples/extensions/body-length-matcher.ts (lines 29–39)

Add an admin API client​

Take Pick<StartedWiremockContainer, "getAdminUrl"> so unit tests can pass a fake:

examples/extensions/stub-count-admin-api.ts
/**
* Calls the route: the number of stubs WireMock serves.
* @throws If the route fails – e.g. because the extension is not registered.
*/
static async count(wiremock: AdminApi): Promise<number> {
const url = `${wiremock.getAdminUrl()}${StubCountAdminApi.ROUTE}`;
const response = await fetch(url);
if (!response.ok) throw new Error(`GET ${url} failed with ${response.status} – is StubCountAdminApi registered?`);
const { count } = (await response.json()) as { count: number };
return count;
}

Source: examples/extensions/stub-count-admin-api.ts (lines 28–38)

Ship a JAR-only extension​

Classes listed in the JAR's META-INF/services load by scanning – provide only the JAR. With withExtensionOptions({ scanning: false }) they need getClassNames().

examples/extensions/powered-by-transformer.ts
/**
* A JAR-only extension: `PoweredByTransformer` is declared in its JAR's `META-INF/services`, so
* WireMock loads it by scanning – no class name needed. It adds `X-Powered-By:
* wiremock-extensions` to every response.
*/
export class PoweredByTransformer implements WireMockExtension {
/** WireMock's name for it. */
static readonly NAME = "powered-by";
/** The response header it adds, and its value. */
static readonly HEADER = "X-Powered-By";
static readonly VALUE = "wiremock-extensions";

getName(): string {
return PoweredByTransformer.NAME;
}

getJars(): WiremockExtensionJar[] {
return [JARS.poweredBy];
}
}

Source: examples/extensions/powered-by-transformer.ts (lines 10–29)

Make it configurable​

Take options in an optional constructor parameter, copy them, and validate them there – WireMock crashes at start-up on a bad value.

examples/extensions/global-response-templating.ts
/**
* A configuration-only extension: no Java, just the WireMock options that switch its built-in
* Handlebars templating on for every response. Register the class for the defaults, or an
* instance to configure it.
*/
export class GlobalResponseTemplating implements WireMockExtension {
/** WireMock's name for its templating transformer. */
static readonly NAME = "response-template";
readonly #options: GlobalResponseTemplatingOptions;

/** @throws If `maxCacheEntries` is not a positive integer – WireMock would crash at start-up. */
constructor(options: GlobalResponseTemplatingOptions = {}) {
const { maxCacheEntries } = options;
if (maxCacheEntries !== undefined && !(Number.isInteger(maxCacheEntries) && maxCacheEntries > 0)) {
throw new RangeError(`maxCacheEntries must be a positive integer, got ${maxCacheEntries}`);
}
this.#options = { ...options };
}

getName(): string {
return GlobalResponseTemplating.NAME;
}

getOptions(): string[] {
const { maxCacheEntries } = this.#options;
return [
"--global-response-templating",
...(maxCacheEntries === undefined ? [] : [`--max-template-cache-entries=${maxCacheEntries}`]),
];
}
}

Source: examples/extensions/global-response-templating.ts (lines 15–45)

Locate JARs​

Resolve JARs next to the module – { module: import.meta.url, file }, or __dirname in CommonJS – never against the working directory:

examples/extensions/jars.ts
/**
* The JARs the example extensions ship in. `{ module: import.meta.url }` resolves them next to
* this file, so tests work from any working directory – and from an npm package.
*/
export const JARS = {
/** `UppercaseTransformer`, `BodyLengthMatcher`, `StubCountAdminApi` – loaded by class name. */
examples: { module: import.meta.url, file: "../__mocks__/extensions/example-extensions.jar" },
/** `PoweredByTransformer`, declared in `META-INF/services` – loaded by scanning. */
poweredBy: { module: import.meta.url, file: "../__mocks__/extensions/powered-by-extension.jar" },
} as const satisfies Record<string, WiremockExtensionJar>;

Source: examples/extensions/jars.ts (lines 12–21)

From an npm package: { package: "@acme/wiremock-extensions", file: "jars/acme.jar" }.

Test it​

Unit tests need no container:

examples/extensions/extensions.test.ts
it.each([
[UppercaseTransformer, "uppercase", [`${JAVA_PACKAGE}.UppercaseTransformer`], [JARS.examples]],
[BodyLengthMatcher, "body-too-long", [`${JAVA_PACKAGE}.BodyLengthMatcher`], [JARS.examples]],
[StubCountAdminApi, "stub-count", [`${JAVA_PACKAGE}.StubCountAdminApi`], [JARS.examples]],
])("%o: a Java class from the example JAR", (Extension, name, classNames, jars) => {
const extension = new Extension();
expect(extension.getName()).toBe(name);
expect(extension.getClassNames()).toEqual(classNames);
expect(extension.getJars()).toEqual(jars);
});

Source: examples/extensions/extensions.test.ts (lines 58–67)

start() checks class names before starting anything:

examples/extensions/extensions.test.ts
it("a class in none of the registered JARs fails start() with a suggestion", async () => {
const typo = new WiremockContainer().withExtensionJar(JARS.examples).withExtension("com.acme.UppercaseTransformer");
await expect(typo.start()).rejects.toThrow(`did you mean "${JAVA_PACKAGE}.UppercaseTransformer"?`);
});

Source: examples/extensions/extensions.test.ts (lines 200–203)

E2E: observe each extension through a real request – examples.

Troubleshooting​

examples/extensions/extensions.test.ts
it.each<[string, () => unknown, string]>([
["an extension's short name instead of its class", () => new WiremockContainer().withExtension("uppercase"), "is not a fully qualified Java class name"],
["an extension with nothing to load", () => new WiremockContainer().withExtension({ getName: () => "empty" }), "it contributes nothing"],
[
"an option split over two entries",
() => new WiremockContainer().withExtension({ getName: () => "journal", getOptions: () => ["--max-request-journal", "2"] }),
'must be "--flag" or "--option=value"',
],
["a JAR that does not exist", () => new WiremockContainer().withExtension(AcmeTransformer), "does not exist"],
["a JAR without the .jar extension", () => new WiremockContainer().withExtensionJar({ ...JARS.examples, file: "../__mocks__/wiremock/mappings/get-payments.json" }), 'must end in ".jar"'],
])("%s", (_, register, message) => {
expect(register).toThrow(message);
});

Source: examples/extensions/extensions.test.ts (lines 184–196)

Error containsFix
is not a fully qualified Java class nameInclude the package – not a short name, path or .class
it contributes nothingImplement getClassNames(), getJars() or getOptions()
must be "--flag" or "--option=value"One entry per option
does not existLocate the JAR with { module: import.meta.url, file }
must end in ".jar"Rename it: { file, name: "x.jar" }
did you mean …? (on start())Fix the class name or register its JAR
another extension named … is already registeredOne configuration per name

WireMock's own errors: ClassNotFoundException – a missing class; UnsupportedClassVersionError – a JAR built for Java newer than 11.

Publish it​

Ship extensions and JARs as an npm package: list the JARs in "files", locate them with { module: import.meta.url, file: "../jars/acme.jar" }, and make @hellaweb3/wiremock-testcontainers-nodejs a peer dependency.