Custom Mocky Balboa client integration
If you need a custom integration for Mocky Balboa, you can use the @mocky-balboa/client
package to integrate with your browser automation framework. There are a few things to keep in mind when setting up the integration:
- Ensure you connect the client to the Mocky Balboa server before executing any tests.
- Listen for error messages on the client and handle them appropriately.
- When you close the browser, make sure to disconnect the client from the Mocky Balboa server.
Installation
- pnpm
- npm
- yarn
pnpm add -D @mocky-balboa/client
npm install -D @mocky-balboa/client
yarn add -D @mocky-balboa/client
Creating and connecting the client
The following example demonstrates how to create and connect a client to the Mocky Balboa server:
- TypeScript
- JavaScript
import {
Client,
MessageType,
type MessageTypes,
type ParsedMessageType,
} from '@mocky-balboa/client';
const client = new Client();
client.on(
MessageType.ERROR,
(message: ParsedMessageType<MessageTypes["ERROR"]>) => {
// Handle the error here.
// Suggestion: Log the error and close the browser
},
);
await client.connect();
import {
Client,
MessageType,
} from '@mocky-balboa/client';
const client = new Client();
client.on(
MessageType.ERROR,
(message) => {
// Handle the error here.
// Suggestion: Log the error and close the browser
},
);
await client.connect();
Passing the client ID to the server
You need to make sure you pass the client ID on every request to the server via a custom header.
- TypeScript
- JavaScript
import { ClientIdentityStorageHeader } from "@mocky-balboa/client";
// This is specific to the integration you are creating
// Here's how the headers are set in Playwright on the browser context
context.setExtraHTTPHeaders({
[ClientIdentityStorageHeader]: client.id,
});
import { ClientIdentityStorageHeader } from "@mocky-balboa/client";
// This is specific to the integration you are creating
// Here's how the headers are set in Playwright on the browser context
context.setExtraHTTPHeaders({
[ClientIdentityStorageHeader]: client.id,
});
Disconnecting the client
Make sure to disconnect the client from the Mocky Balboa server when you are done with it, i.e. when the test finished (either fails or passes).
- TypeScript
- JavaScript
client.disconnect();
client.disconnect();
Injecting a client route handler
To re-use the same route handler interface for both client and server side network requests, you can inject a client route handler into the client instance. This expects a function callback in the implementing framework that can accept arbitrary arguments and returns any response. It is on you to transform the incoming arguments to a Request
object that can be used by Mocky Balboa internally, and transform the ExternalRouteHandlerRouteResponse
to the appropriate response for your framework.
For an example of this see the Playwright integration code.