### Spin up New Server Instance for Parallel Tests (JavaScript) Source: https://docs.mockybalboa.com/docs/server/next-js This JavaScript example demonstrates how to spin up a new server instance for each test using Playwright and Mocky Balboa. It includes utility functions to find free ports, start the server, wait for it to be ready, and clean up afterwards. Dependencies include @playwright/test, @mocky-balboa/playwright, get-port, detect-port, and node:child_process. ```javascript import { test, expect } from "@playwright/test"; import { createClient } from "@mocky-balboa/playwright"; import getPort from "get-port"; import { detect } from "detect-port"; import { spawn } from "node:child_process"; // Waits for a port to be occupied checking once every second for // a maximum of 10 seconds. const waitForPortToBeOccupied = async (port) => { const waitFor = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); let ticks = 0; while (ticks < 10) { await waitFor(1000); const realPort = await detect(port); if (realPort !== port) { return; } ticks++; } throw new Error(`Timed out waiting for port ${port} to be occupied`); }; let client; let applicationPort; let serverProcess; test.beforeEach(async ({ context }) => { // Find a free port for the application applicationPort = await getPort(); // Find a free port for the websocket server const websocketServerPort = await getPort(); console.log( `Starting server on port ${applicationPort} and websocket port ${websocketServerPort}`, ); // Start the Next.js server via Mocky Balboa serverProcess = spawn("pnpm", [ "mocky-balboa-next-js", "--port", applicationPort.toString(), "--websocket-port", websocketServerPort.toString(), ]); // Log all stdout from the server process serverProcess.stdout.on("data", (data) => { console.log(data.toString()); }); // Log all stderr from the server process serverProcess.stderr.on("data", (data) => { console.error(data.toString()); }); ``` -------------------------------- ### Usage with Fastify (JavaScript) Source: https://docs.mockybalboa.com/docs/server/fastify Provides a JavaScript example for integrating Mocky Balboa with a Fastify server. It shows the setup for registering the middleware and initiating the Mocky Balboa server alongside the Fastify application. ```javascript import Fastify from "fastify"; import fastifyExpress from "@fastify/express"; import { mockyBalboaMiddleware, startServer } from "@mocky-balboa/server"; (async () => { const app = Fastify(); await fastify.register(fastifyExpress); // Register the Mocky Balboa middleware app.use(mockyBalboaMiddleware()); // Start the Mocky Balboa server. // Pass optional server options here: // https://api-reference.mockybalboa.com/functions/_mocky-balboa_server.startServer await startServer(); // Your app goes here app.listen({ port: 3000 }); })(); ``` -------------------------------- ### Use Mocky Balboa Middleware with Koa (JavaScript) Source: https://docs.mockybalboa.com/docs/server/koa Demonstrates how to register the Mocky Balboa middleware within a Koa application and start the Mocky Balboa server. This example is written in JavaScript. ```javascript import Koa from "koa"; import { mockyBalboaMiddleware, startServer } from "@mocky-balboa/server"; (async () => { const app = new Koa(); // Register the Mocky Balboa middleware app.use(mockyBalboaMiddleware()); // Start the Mocky Balboa server. // Pass optional server options here: // https://api-reference.mockybalboa.com/functions/_mocky-balboa_server.startServer await startServer(); // Your app goes here app.listen(3000); })(); ``` -------------------------------- ### Spin up New Server Instance for Parallel Tests (TypeScript) Source: https://docs.mockybalboa.com/docs/server/next-js This TypeScript example demonstrates how to spin up a new server instance for each test using Playwright and Mocky Balboa. It includes utility functions to find free ports, start the server, wait for it to be ready, and clean up afterwards. Dependencies include @playwright/test, @mocky-balboa/playwright, get-port, detect-port, and node:child_process. ```typescript import { test, expect } from "@playwright/test"; import { createClient, type Client } from "@mocky-balboa/playwright"; import getPort from "get-port"; import { detect } from "detect-port"; import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; // Waits for a port to be occupied checking once every second for // a maximum of 10 seconds. const waitForPortToBeOccupied = async (port: number) => { const waitFor = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); let ticks = 0; while (ticks < 10) { await waitFor(1000); const realPort = await detect(port); if (realPort !== port) { return; } ticks++; } throw new Error(`Timed out waiting for port ${port} to be occupied`); }; let client: Client; let applicationPort: number; let serverProcess: ChildProcessWithoutNullStreams; test.beforeEach(async ({ context }) => { // Find a free port for the application applicationPort = await getPort(); // Find a free port for the websocket server const websocketServerPort = await getPort(); console.log( `Starting server on port ${applicationPort} and websocket port ${websocketServerPort}`, ); // Start the Next.js server via Mocky Balboa serverProcess = spawn("pnpm", [ "mocky-balboa-next-js", "--port", applicationPort.toString(), "--websocket-port", websocketServerPort.toString(), ]); // Log all stdout from the server process serverProcess.stdout.on("data", (data) => { console.log(data.toString()); }); // Log all stderr from the server process serverProcess.stderr.on("data", (data) => { console.error(data.toString()); }); // Wait for the server processes to be ready await Promise.all([ waitForPortToBeOccupied(applicationPort), waitForPortToBeOccupied(websocketServerPort), ]); // Create the Mocky Balboa Playwright client to run against // the server we just started client = await createClient(context, { port: websocketServerPort, }); }); test.afterEach(async () => { // Kill the server process after each test serverProcess.kill(); }); test("...", async ({ page, }) => { // Visit pages on the server we started await page.goto(`http://localhost:${applicationPort}`); }); ``` -------------------------------- ### Use Mocky Balboa Middleware with Koa (TypeScript) Source: https://docs.mockybalboa.com/docs/server/koa Demonstrates how to register the Mocky Balboa middleware within a Koa application and start the Mocky Balboa server. This example is written in TypeScript. ```typescript import Koa from "koa"; import { mockyBalboaMiddleware, startServer } from "@mocky-balboa/server"; void (async () => { const app = new Koa(); // Register the Mocky Balboa middleware app.use(mockyBalboaMiddleware()); // Start the Mocky Balboa server. // Pass optional server options here: // https://api-reference.mockybalboa.com/functions/_mocky-balboa_server.startServer await startServer(); // Your app goes here app.listen(3000); })(); ``` -------------------------------- ### Install Mocky Balboa SvelteKit Package Source: https://docs.mockybalboa.com/docs/server/sveltekit Installs the Mocky Balboa SvelteKit package as a development dependency using pnpm, npm, or yarn. ```shell pnpm add -D @mocky-balboa/sveltekit ``` ```shell npm install -D @mocky-balboa/sveltekit ``` ```shell yarn add -D @mocky-balboa/sveltekit ``` -------------------------------- ### Install Astro Node Adapter Source: https://docs.mockybalboa.com/docs/server/astro Installs the `@astrojs/node` adapter, which is required for building the server for testing purposes with Mocky Balboa. This is not needed if only running tests in dev mode, but it's recommended for production environments. ```shell pnpm add -D @astrojs/node ``` ```shell npm install -D @astrojs/node ``` ```shell yarn add -D @astrojs/node ``` -------------------------------- ### Install Mocky Balboa Cypress Plugin Source: https://docs.mockybalboa.com/docs/client/cypress Installs the Mocky Balboa Cypress plugin as a development dependency using different package managers. ```pnpm pnpm add -D @mocky-balboa/cypress ``` ```npm npm install -D @mocky-balboa/cypress ``` ```yarn yarn add -D @mocky-balboa/cypress ``` -------------------------------- ### Install Mocky Balboa Server with npm Source: https://docs.mockybalboa.com/docs/server/express Installs the Mocky Balboa server as a development dependency using the npm package manager. This is the standard installation command for npm users. ```bash npm install -D @mocky-balboa/server ``` -------------------------------- ### Server Initialization and Playwright Client Creation (JavaScript) Source: https://docs.mockybalboa.com/docs/server/next-js This snippet demonstrates waiting for server processes to become ready on specified ports and then creating a Playwright client to interact with the started server. It assumes the existence of `waitForPortToBeOccupied` and `createClient` functions. ```javascript await Promise.all([ waitForPortToBeOccupied(applicationPort), waitForPortToBeOccupied(websocketServerPort), ]); client = await createClient(context, { port: websocketServerPort, }); ``` -------------------------------- ### Serve SvelteKit Application with Mocky Balboa Source: https://docs.mockybalboa.com/docs/server/sveltekit Serves the built SvelteKit application using the `mocky-balboa-sveltekit` command, which starts an Express server with Mocky Balboa integration. Available for pnpm, npm, and yarn. ```shell pnpm mocky-balboa-sveltekit ``` ```shell npm mocky-balboa-sveltekit ``` ```shell yarn mocky-balboa-sveltekit ``` -------------------------------- ### Install @mocky-balboa/client with npm Source: https://docs.mockybalboa.com/docs/client/custom Installs the @mocky-balboa/client package as a development dependency using npm. This package is required for custom Mocky Balboa integrations. ```bash npm install -D @mocky-balboa/client ``` -------------------------------- ### Install Mocky Balboa Server with yarn Source: https://docs.mockybalboa.com/docs/server/express Installs the Mocky Balboa server as a development dependency using the yarn package manager. Use this command if your project utilizes yarn for dependency management. ```bash yarn add -D @mocky-balboa/server ``` -------------------------------- ### Programmatically Start Mocky Balboa Servers with Next.js (TypeScript) Source: https://docs.mockybalboa.com/docs/server/next-js Programmatically starts Mocky Balboa servers alongside your Next.js application using the `startServers` function. This method is useful for custom configurations and allows integration within existing server processes. It requires importing `startServers` and the `next` function, along with your Next.js configuration. ```typescript import { startServers } from "@mocky-balboa/next-js"; import next from "next"; import nextConfig from "../path/to/next.config.js"; const main = async () => { await startServers( (options) => { return next({ ...options, // If you want to enable experimental features that are available to enable via the options // experimentalHttpsServer: true, // experimentalTestProxy: true, conf: nextConfig, }); }, ); }; void main(); ``` -------------------------------- ### Usage: Mocky Balboa with Express (JavaScript) Source: https://docs.mockybalboa.com/docs/server/express Provides a JavaScript example of integrating Mocky Balboa middleware into an Express.js application. This snippet illustrates the necessary imports, middleware setup, and server initialization. ```javascript import express from "express"; import { mockyBalboaMiddleware, startServer } from "@mocky-balboa/server"; (async () => { const app = express(); // Register the Mocky Balboa middleware app.use(mockyBalboaMiddleware()); // Start the Mocky Balboa server. // Pass optional server options here: // https://api-reference.mockybalboa.com/functions/_mocky-balboa_server.startServer await startServer(); // Your app goes here app.listen(3000); })(); ``` -------------------------------- ### Run Mocky Balboa CLI with Next.js Source: https://docs.mockybalboa.com/docs/server/next-js Starts the Next.js server along with the necessary Mocky Balboa servers using the command-line interface. This is the recommended method for ease of use. The CLI automatically detects your Next.js configuration file. ```bash pnpm mocky-balboa-next-js ``` ```bash npm mocky-balboa-next-js ``` ```bash yarn mocky-balboa-next-js ``` -------------------------------- ### Install @mocky-balboa/client with pnpm Source: https://docs.mockybalboa.com/docs/client/custom Installs the @mocky-balboa/client package as a development dependency using pnpm. This package is essential for custom integrations with Mocky Balboa. ```bash pnpm add -D @mocky-balboa/client ``` -------------------------------- ### Install Mocky Balboa Playwright Package Source: https://docs.mockybalboa.com/docs/client/playwright Installs the Mocky Balboa Playwright package as a development dependency using different package managers. ```bash pnpm add -D @mocky-balboa/playwright ``` ```bash npm install -D @mocky-balboa/playwright ``` ```bash yarn add -D @mocky-balboa/playwright ``` -------------------------------- ### Install @mocky-balboa/client with yarn Source: https://docs.mockybalboa.com/docs/client/custom Installs the @mocky-balboa/client package as a development dependency using yarn. This package is necessary for custom Mocky Balboa integrations. ```bash yarn add -D @mocky-balboa/client ``` -------------------------------- ### Install Mocky Balboa Server with pnpm Source: https://docs.mockybalboa.com/docs/server/express Installs the Mocky Balboa server as a development dependency using the pnpm package manager. This command is typically used in projects managed with pnpm. ```bash pnpm add -D @mocky-balboa/server ``` -------------------------------- ### Install Mocky Balboa Vite Plugin with pnpm Source: https://docs.mockybalboa.com/docs/server/vite Installs the Mocky Balboa Vite plugin as a development dependency using pnpm. This command is suitable for projects managed with pnpm. ```bash pnpm add -D @mocky-balboa/vite ``` -------------------------------- ### Install @mocky-balboa/server Package Source: https://docs.mockybalboa.com/docs/server/custom Installs the Mocky Balboa server package as a development dependency. This package is essential for creating custom server integrations. ```bash pnpm add -D @mocky-balboa/server ``` ```bash npm install -D @mocky-balboa/server ``` ```bash yarn add -D @mocky-balboa/server ``` -------------------------------- ### Install Mocky Balboa Vite Plugin with yarn Source: https://docs.mockybalboa.com/docs/server/vite Installs the Mocky Balboa Vite plugin as a development dependency using yarn. This command is suitable for projects managed with yarn. ```bash yarn add -D @mocky-balboa/vite ``` -------------------------------- ### Serve React Router Application with Mocky Balboa Source: https://docs.mockybalboa.com/docs/server/react-router Starts a development server for the React Router application using Mocky Balboa, serving the built application from a specified directory. ```bash pnpm mocky-balboa-react-router ``` ```bash npm mocky-balboa-react-router ``` ```bash yarn mocky-balboa-react-router ``` -------------------------------- ### Install Mocky Balboa React Router Source: https://docs.mockybalboa.com/docs/server/react-router Installs the Mocky Balboa React Router package as a development dependency using different package managers. ```bash pnpm add -D @mocky-balboa/react-router ``` ```bash npm install -D @mocky-balboa/react-router ``` ```bash yarn add -D @mocky-balboa/react-router ``` -------------------------------- ### Install Mocky Balboa Vite Plugin with npm Source: https://docs.mockybalboa.com/docs/server/vite Installs the Mocky Balboa Vite plugin as a development dependency using npm. This command is suitable for projects managed with npm. ```bash npm install -D @mocky-balboa/vite ``` -------------------------------- ### Install Mocky Balboa Next.js Package Source: https://docs.mockybalboa.com/docs/server/next-js Installs the Mocky Balboa Next.js integration package as a development dependency. This package provides tools to run Mocky Balboa alongside your Next.js application. ```bash pnpm add -D @mocky-balboa/next-js ``` ```bash npm install -D @mocky-balboa/next-js ``` ```bash yarn add -D @mocky-balboa/next-js ``` -------------------------------- ### Start Mocky Balboa Server (TypeScript/JavaScript) Source: https://docs.mockybalboa.com/docs/server/custom Starts the Mocky Balboa server within the same process as your application server. This is a prerequisite for Mock Service Worker to intercept network requests effectively. ```typescript import { startServer, } from "@mocky-balboa/server"; await startServer(); ``` ```javascript import { startServer, } from "@mocky-balboa/server"; await startServer(); ``` -------------------------------- ### Serve Astro Application with Mocky Balboa Source: https://docs.mockybalboa.com/docs/server/astro Serves the built Astro application using the `mocky-balboa-astro` command. This command starts a Node.js http server powered by Express and includes the necessary Mocky Balboa servers. ```shell pnpm mocky-balboa-astro ``` ```shell npm mocky-balboa-astro ``` ```shell yarn mocky-balboa-astro ``` -------------------------------- ### Usage with Fastify (TypeScript) Source: https://docs.mockybalboa.com/docs/server/fastify Demonstrates how to use Mocky Balboa middleware and start its server within a Fastify application using TypeScript. It registers the express compatibility layer and applies the Mocky Balboa middleware before starting the Fastify server. ```typescript import Fastify from "fastify"; import fastifyExpress from "@fastify/express"; import { mockyBalboaMiddleware, startServer } from "@mocky-balboa/server"; void (async () => { const app = Fastify(); await fastify.register(fastifyExpress); // Register the Mocky Balboa middleware app.use(mockyBalboaMiddleware()); // Start the Mocky Balboa server. // Pass optional server options here: // https://api-reference.mockybalboa.com/functions/_mocky-balboa_server.startServer await startServer(); // Your app goes here app.listen({ port: 3000 }); })(); ``` -------------------------------- ### Install Mocky Balboa Astro Package Source: https://docs.mockybalboa.com/docs/server/astro Installs the Mocky Balboa Astro integration package using different package managers. This package is essential for enabling Mocky Balboa's features within an Astro project. ```shell pnpm add -D @mocky-balboa/astro ``` ```shell npm install -D @mocky-balboa/astro ``` ```shell yarn add -D @mocky-balboa/astro ``` -------------------------------- ### Install Mocky Balboa Nuxt Module Source: https://docs.mockybalboa.com/docs/server/nuxt Installs the Mocky Balboa Nuxt module as a development dependency using different package managers. This module is essential for integrating Mocky Balboa's features into your Nuxt.js application. ```pnpm pnpm add -D @mocky-balboa/nuxt ``` ```npm npm install -D @mocky-balboa/nuxt ``` ```yarn yarn add -D @mocky-balboa/nuxt ``` -------------------------------- ### Usage: Mocky Balboa with Express (TypeScript) Source: https://docs.mockybalboa.com/docs/server/express Demonstrates how to use Mocky Balboa middleware within an Express.js application written in TypeScript. It shows the import statements, middleware registration, and starting the Express server. ```typescript import express from "express"; import { mockyBalboaMiddleware, startServer } from "@mocky-balboa/server"; void (async () => { const app = express(); // Register the Mocky Balboa middleware app.use(mockyBalboaMiddleware()); // Start the Mocky Balboa server. // Pass optional server options here: // https://api-reference.mockybalboa.com/functions/_mocky-balboa_server.startServer await startServer(); // Your app goes here app.listen(3000); })(); ``` -------------------------------- ### Differentiate GraphQL Requests in Route Handler (Playwright & Cypress) Source: https://docs.mockybalboa.com/docs/common-use-cases This snippet demonstrates how to differentiate between multiple requests to the same route handler, such as a GraphQL endpoint, by inspecting the `operationName` from the request payload. It provides examples for both Playwright and Cypress testing frameworks, allowing you to define specific responses based on the operation being performed. ```playwright import test from "@mocky-balboa/playwright/test"; test("...", ({ mocky }) => { mocky.route("https://myservice.com/graphql", async (route) => { const { operationName } = await route.request.json(); switch (operationName) { case "getUser": return route.fulfill({ status: 200, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: { user: { id: "user-id", name: "John Doe", email: "john.doe@example.com", }, }, errors: [], }), }); case "createUser": return route.fulfill({ status: 201, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: { createUser: { id: "new-user-id", name: "Jane Doe", email: "jane.doe@example.com", }, }, errors: [], }), }); } // Define a fallback behaviour for when the operationName is not recognized return route.passthrough(); }); }); ``` ```cypress it("...", () => { cy.mocky((mocky) => { mocky.route("https://myservice.com/graphql", (route) => { const { operationName } = await route.request.json(); switch (operationName) { case "getUser": return route.fulfill({ status: 200, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: { user: { id: "user-id", name: "John Doe", email: "john.doe@example.com", }, }, errors: [], }), }); case "createUser": return route.fulfill({ status: 201, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: { createUser: { id: "new-user-id", name: "Jane Doe", email: "jane.doe@example.com", }, }, errors: [], }), }); } // Define a fallback behaviour for when the operationName is not recognized return route.passthrough(); }); }); }); ``` -------------------------------- ### Configure Mocky Balboa Integration in Astro Source: https://docs.mockybalboa.com/docs/server/astro Configures the Mocky Balboa integration within the Astro configuration file (`astro.config.ts` or `astro.config.js`). This setup includes enabling the integration and optionally configuring the Node.js adapter for server-side rendering. ```typescript import { defineConfig } from "astro/config"; import node from "@astrojs/node"; import mockyBalboa from "@mocky-balboa/astro"; // https://astro.build/config export default defineConfig({ integrations: [mockyBalboa()], // You need to use the node adapter to build the server for running tests against // If you are only running tests in dev mode (not recommended outside of local development), // then you don't need to use the node adapter adapter: node({ // Make sure to build the server as middleware mode: "middleware", }), }); ``` ```javascript import { defineConfig } from "astro/config"; import node from "@astrojs/node"; import mockyBalboa from "@mocky-balboa/astro"; // https://astro.build/config export default defineConfig({ integrations: [mockyBalboa()], // You need to use the node adapter to build the server for running tests against // If you are only running tests in dev mode (not recommended outside of local development), // then you don't need to use the node adapter adapter: node({ // Make sure to build the server as middleware mode: "middleware", }), }); ``` -------------------------------- ### Mocky Balboa SvelteKit CLI Help Source: https://docs.mockybalboa.com/docs/server/sveltekit Displays the help information for the `mocky-balboa-sveltekit` command-line interface, showing available options for running the server. ```shell Usage: mocky-balboa-sveltekit [options] [dist-dir] Starts a Node.js http server powered by Express for your SvelteKit application as well as the necessary mocky-balboa servers Arguments: dist-dir Path to the directory where your SvelteKit application is built (default: "build") Options: -p, --port [port] Port to run the server on (default: "3000") --websocket-port [websocketPort] Port to run the WebSocket server on (default: "58152") -h, --hostname [hostname] Hostname to bind the server to (default: "0.0.0.0") -t, --timeout [timeout] Timeout in milliseconds for the mock server to receive a response from the client (default: "5000") --https Enable https server. Either https or http server is run, not both. When no --https-cert and --https-key are provided, a self-signed certificate will be automatically generated. --https-cert [certPath] Optional path to the https certificate file --https-ca [caPath] Optional path to the https Certificate Authority file --https-key [keyPath] Optional path to the https key file --help display help for command ``` -------------------------------- ### Create and connect Mocky Balboa client (JavaScript) Source: https://docs.mockybalboa.com/docs/client/custom Shows how to instantiate the Mocky Balboa client and connect to the server. It also sets up a listener for error messages from the client. ```javascript 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(); ``` -------------------------------- ### Build SvelteKit Application Source: https://docs.mockybalboa.com/docs/server/sveltekit Builds the SvelteKit application for production using the standard Vite build command, compatible with pnpm, npm, and yarn. ```shell pnpm vite build ``` ```shell npm vite build ``` ```shell yarn vite build ``` -------------------------------- ### Build React Router Application Source: https://docs.mockybalboa.com/docs/server/react-router Builds the React Router application for production deployment using the standard build command. ```bash pnpm react-router build ``` ```bash npm react-router build ``` ```bash yarn react-router build ``` -------------------------------- ### Mocky Balboa Astro Server Options Source: https://docs.mockybalboa.com/docs/server/astro Provides a detailed list of command-line options available for the `mocky-balboa-astro` command, including port configuration, hostname, timeouts, HTTPS settings, and base path adjustments. ```shell Usage: mocky-balboa-astro [options] [dist-dir] Starts a Node.js http server powered by Express for your Astro application as well as the necessary mocky-balboa servers Arguments: dist-dir Path to the directory where your Astro application is built (default: "dist") Options: -p, --port [port] Port to run the server on (default: "3000") --websocket-port [websocketPort] Port to run the WebSocket server on (default: "58152") -h, --hostname [hostname] Hostname to bind the server to (default: "0.0.0.0") -t, --timeout [timeout] Timeout in milliseconds for the mock server to receive a response from the client (default: "5000") --https Enable https server. Either https or http server is run, not both. When no --https-cert and --https-key are provided, a self-signed certificate will be automatically generated. --https-cert [certPath] Optional path to the https certificate file --https-ca [caPath] Optional path to the https Certificate Authority file --https-key [keyPath] Optional path to the https key file -b, --base [base] Change this based on your astro.config.mjs, `base` option. They should match. (default: "/") --help display help for command ``` -------------------------------- ### Configure SvelteKit Adapter for Node Source: https://docs.mockybalboa.com/docs/server/sveltekit Configures the SvelteKit project to use the Node adapter for building the application, which is required for serving with Mocky Balboa. ```javascript // svelte.config.js import adapter from "@sveltejs/adapter-node"; import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: vitePreprocess(), kit: { adapter: adapter(), }, }; export default config; ``` -------------------------------- ### Create and connect Mocky Balboa client (TypeScript) Source: https://docs.mockybalboa.com/docs/client/custom Demonstrates creating a new Mocky Balboa client instance and establishing a connection to the Mocky Balboa server. It also includes setting up an error handler for 'ERROR' messages. ```typescript import { Client, MessageType, type MessageTypes, type ParsedMessageType, } from '@mocky-balboa/client'; const client = new Client(); client.on( MessageType.ERROR, (message: ParsedMessageType) => { // Handle the error here. // Suggestion: Log the error and close the browser }, ); await client.connect(); ``` -------------------------------- ### Configure Mocky Balboa Client Connection Options Source: https://docs.mockybalboa.com/docs/client/cypress Shows how to customize the connection options for the Mocky Balboa client using the `cy.mockySetConnectionOptions` command. This command must be called before `cy.mocky`. ```typescript it("...", async () => { // Make sure you call mockySetConnectionOptions before any calls to cy.mocky cy.mockySetConnectionOptions({ port: 1234 }); cy.mocky((mocky) => { // ... }); }); ``` ```javascript it("...", async () => { // Make sure you call mockySetConnectionOptions before any calls to cy.mocky cy.mockySetConnectionOptions({ port: 1234 }); cy.mocky((mocky) => { // ... }); }); ``` -------------------------------- ### Mock API Routes with cy.mocky Source: https://docs.mockybalboa.com/docs/client/cypress Demonstrates how to use the `cy.mocky` command to define mock API routes within your Cypress tests. It accepts a callback where you can set up routes and their responses, and then visits the application to test the mock. ```typescript it("loads the correct users", async () => { cy.mocky((mocky) => { mocky.route("**/api/users", (route) => { return route.fulfill({ status: 200, body: JSON.stringify([ { id: "user-1", name: "John Doe" }, { id: "user-2", name: "Jane Doe" } ]), headers: { "Content-Type": "application/json" }, }); }); }); // Visit the page of our application in the browser cy.visit("/"); // Our mock above should have been returned on our server cy.contains("John Doe"); }); ``` ```javascript it("loads the correct users", async () => { cy.mocky((mocky) => { mocky.route("**/api/users", (route) => { return route.fulfill({ status: 200, body: JSON.stringify([ { id: "user-1", name: "John Doe" }, { id: "user-2", name: "Jane Doe" } ]), headers: { "Content-Type": "application/json" }, }); }); }); // Visit the page of our application in the browser cy.visit("/"); // Our mock above should have been returned on our server cy.contains("John Doe"); }); ``` -------------------------------- ### Configure Mocky Balboa Nuxt Module Source: https://docs.mockybalboa.com/docs/server/nuxt Configures the Mocky Balboa Nuxt module within your Nuxt application's configuration file. This setup enables the module, with an option to disable it for production environments. Ensure 'enabled' is set to 'false' for production builds. ```typescript // nuxt.config.ts export default defineNuxtConfig({ // Enabled defaults to true modules: [["@mocky-balboa/nuxt", { enabled: true }]], }); ``` ```javascript // nuxt.config.js export default defineNuxtConfig({ // Enabled defaults to true modules: [["@mocky-balboa/nuxt", { enabled: true }]], }); ``` -------------------------------- ### Build Astro Application Source: https://docs.mockybalboa.com/docs/server/astro Builds the Astro application for production using the `astro build` command. Ensure the Mocky Balboa integration is enabled in your Astro configuration before running this command. ```shell pnpm astro build ``` ```shell npm astro build ``` ```shell yarn astro build ``` -------------------------------- ### Navigating to Server URL in Playwright Test (JavaScript) Source: https://docs.mockybalboa.com/docs/server/next-js This snippet shows how to navigate a Playwright page to a specific URL served by the application. It constructs the URL using the `applicationPort` and assumes a `page` object is available within the test context. ```javascript test("...", async ({ page, }) => { await page.goto(`http://localhost:${applicationPort}`); }); ``` -------------------------------- ### Connect to Mocky Balboa Server with Playwright Source: https://docs.mockybalboa.com/docs/advanced Establishes a connection to the Mocky Balboa server using the Playwright integration. This involves creating a client instance and calling the connect method, which is abstracted away for users. It sets extra HTTP headers on the browser context to match outbound requests. ```typescript import { test } from "@playwright/test"; import { createClient } from "@mocky-balboa/playwright"; test("my page loads", async ({ context, page }) => { const client = await createClient(context); }); ``` ```javascript import { test } from "@playwright/test"; import { createClient } from "@mocky-balboa/playwright"; test("my page loads", async ({ context, page }) => { const client = await createClient(context); }); ``` -------------------------------- ### Playwright Test with Client Mocking Source: https://docs.mockybalboa.com/docs/changelogs/%40mocky-balboa-playwright Demonstrates how to import and use the Playwright test utility to access mocky client instances directly within tests. This allows for easy configuration of mocked routes during test execution. It requires the '@mocky-balboa/playwright/test' module. ```javascript import test from "@mocky-balboa/playwright/test"; test("my test", ({ mocky }) => { mocky .route //... (); }); ``` -------------------------------- ### Use Custom Mocking Commands in Cypress Source: https://docs.mockybalboa.com/docs/changelogs/%40mocky-balboa-cypress This snippet demonstrates how to import and use custom commands provided by @mocky-balboa/cypress in your Cypress support file. It enables client-side mocking within your tests by defining routes and their mock responses. ```javascript import "@mocky-balboa/cypress/commands"; it("does something", () => { cy.mocky((mocky) => { mocky .route //... configuration for mocking (); }); }); ``` -------------------------------- ### Load Page with Playwright Source: https://docs.mockybalboa.com/docs/advanced Navigates the Playwright page to a specified URL. This action triggers network requests that can be intercepted and handled by Mocky Balboa's registered fixtures. ```typescript await page.goto("http://localhost:8080"); ``` ```javascript await page.goto("http://localhost:8080"); ``` -------------------------------- ### Configure React Router for SSR Source: https://docs.mockybalboa.com/docs/server/react-router Sets up the React Router configuration file to enable Server-Side Rendering (SSR) mode. ```typescript // react-router.config.js import type { Config } from "@react-router/dev/config"; export default { ssr: true, } satisfies Config; ``` ```javascript // react-router.config.js /** @type {import('@react-router/dev/config').Config} */ export default { ssr: true, }; ``` -------------------------------- ### Mock Binary Response with Playwright Source: https://docs.mockybalboa.com/docs/common-use-cases Shows how to mock binary responses using Mocky Balboa with Playwright by specifying a file path. The content type is automatically inferred from the file extension. ```typescript import test from "@mocky-balboa/playwright/test"; test("..."), ({ mocky }) => { mocky.route("**/user/*/profile-image", (route) => { return route.fulfill({ path: "/path/to/image.png", }); }); }); ``` -------------------------------- ### Assert on Requests with cy.mockyWaitForRequest Source: https://docs.mockybalboa.com/docs/client/cypress Demonstrates how to use `cy.mockyWaitForRequest` to wait for a specific API request and assert on its properties, such as headers. It takes an action to trigger the request and the request URL pattern. ```typescript it("calls /api/users with the correct public API key", async () => { cy .mockyWaitForRequest(() => cy.visit("/"), "**/api/users") .then((request) => { expect(request.headers.get("X-Public-Api-Key")).to.equal( "public-api-key", ); }); }); ``` ```javascript it("calls /api/users with the correct public API key", async () => { cy .mockyWaitForRequest(() => cy.visit("/"), "**/api/users") .then((request) => { expect(request.headers.get("X-Public-Api-Key")).to.equal( "public-api-key", ); }); }); ``` -------------------------------- ### Fulfill with File - TypeScript Source: https://docs.mockybalboa.com/docs/client-guide/route Fulfills the response using a file, supporting any file type for mocking binary data. The Content-Type header is inferred from the file extension if not explicitly set. ```typescript client.route("**/api", (route) => { return route.fulfill({ path: "/path/to/file.json", }); }); ``` -------------------------------- ### Create Mocky Balboa Client Instance Manually (TypeScript) Source: https://docs.mockybalboa.com/docs/client/playwright Demonstrates creating a standalone Mocky Balboa client instance without relying on Playwright's `test.extend`. This is useful when testing applications that don't have an embedded Mocky Balboa server or when managing multiple test suites. Connection options can be optionally passed during client creation. ```typescript import { test, expect } from "@playwright/test"; import { createClient } from "@mocky-balboa/playwright"; test("my page loads", async ({ page }) => { // Optionally pass connection options here const mocky = createClient(); // Register our fixture on routes matching '**/api/users' mocky.route("**/api/users", (route) => { return route.fulfill({ status: 200, body: JSON.stringify([ { id: "user-1", name: "John Doe" }, { id: "user-2", name: "Jane Doe" } ]), headers: { "Content-Type": "application/json" }, }); }); // Visit the page of our application in the browser await page.goto("http://localhost:3000"); // Our mock above should have been returned on our server await expect(page.getByText("John Doe")).toBeVisible(); }); ``` -------------------------------- ### Mock Request a Specific Number of Times (Cypress) Source: https://docs.mockybalboa.com/docs/common-use-cases Demonstrates how to mock an API request ('**/api/data') to be called only a specific number of times using the `times` option with `cy.mocky` in Cypress. This is useful for sequential API calls with varying responses. ```javascript it("...", () => { cy.mocky((mocky) => { mocky.route("**/api/data", (route) => { return route.fulfill({ // ... }); // The route handler will only be called once if the route matches }, { times: 1 }); }); }); ``` -------------------------------- ### Register Mocky Balboa Cypress Commands Source: https://docs.mockybalboa.com/docs/client/cypress Imports the Mocky Balboa Cypress commands into the E2E test support file to make them available in your tests. This is typically done in `cypress/support/e2e.{js,jsx,ts,tsx}`. ```typescript // cypress/support/e2e.ts import "@mocky-balboa/cypress/commands"; ``` ```javascript // cypress/support/e2e.js import "@mocky-balboa/cypress/commands"; ``` -------------------------------- ### Assert Request Body and Headers with Cypress Source: https://docs.mockybalboa.com/docs/common-use-cases Illustrates how to use Mocky Balboa with Cypress to verify request bodies and headers. This approach allows for flexible assertion within your Cypress test suite. ```javascript it("calls the API with the correct request body", () => { cy .mockyWaitForRequest( () => { return cy.visit("/"); }, "**/api/data" ) .then((request) => { const body = await request.json(); expect(body).to.equal({ id: "request-id" }); }); }); it("calls the API with the correct request headers", () => { cy .mockyWaitForRequest( () => { return cy.visit("/"); }, "**/api/data", { timeout: 8000, } ) .then((request) => { expect(request.headers.get("x-custom-header")).to.equal("custom-value") }); }); ``` -------------------------------- ### Server Process Cleanup After Test (JavaScript) Source: https://docs.mockybalboa.com/docs/server/next-js This code snippet defines the cleanup logic to be executed after each test. It ensures that the server process is killed to prevent resource leaks and maintain a clean state for subsequent tests. ```javascript test.afterEach(async () => { serverProcess.kill(); }); ``` -------------------------------- ### Enable Mocky Balboa Vite Plugin in vite.config Source: https://docs.mockybalboa.com/docs/server/sveltekit Enables the Mocky Balboa Vite plugin in the Vite configuration file for development mode. This applies to both TypeScript and JavaScript configurations. ```javascript // vite.config.ts import { defineConfig } from "vite"; import { sveltekit } from "@sveltejs/kit/vite"; import mockyBalboa from "@mocky-balboa/sveltekit"; export default defineConfig({ plugins: [sveltekit(), mockyBalboa()], }); ``` ```javascript // vite.config.js import { defineConfig } from "vite"; import { sveltekit } from "@sveltejs/kit/vite"; import mockyBalboa from "@mocky-balboa/sveltekit"; export default defineConfig({ plugins: [sveltekit(), mockyBalboa()], }); ``` -------------------------------- ### Register Network Fixture with Mocky Balboa Client Source: https://docs.mockybalboa.com/docs/advanced Registers a network fixture directly on the Mocky Balboa client to handle external API calls. This code defines how the client should respond when a specific endpoint (e.g., '**/api/users') is requested, including the status, body, and headers of the response. ```typescript client.route("**/api/users", (route) => { return route.fulfill({ status: 200, body: JSON.stringify([ { id: "user-1", name: "John Doe" }, { id: "user-2", name: "Jane Doe" } ]), headers: { "Content-Type": "application/json" }, }); }); ``` ```javascript client.route("**/api/users", (route) => { return route.fulfill({ status: 200, body: JSON.stringify([ { id: "user-1", name: "John Doe" }, { id: "user-2", name: "Jane Doe" } ]), headers: { "Content-Type": "application/json" }, }); }); ``` -------------------------------- ### Route Handling with Request Inspection Source: https://docs.mockybalboa.com/docs/client-guide/route Demonstrates how to define a route using `client.route` and inspect the `request.method` to conditionally fulfill the request. This allows for different responses based on the HTTP method used. ```APIDOC ## POST /websites/mockybalboa/api ### Description This endpoint allows you to define a route that matches any path ending in '/api'. It inspects the incoming request's HTTP method. If the method is 'GET', it fulfills the request with a JSON body of `{"hello": "world"}`. For any other HTTP method, it fulfills the request with a JSON body of `{"hello": "again world"}`. ### Method POST (demonstrated, but applicable to other methods) ### Endpoint `/websites/mockybalboa/api` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (The example shows fulfillment logic, not a request body for the route definition itself) ### Request Example ```javascript client.route("**/api", (route) => { const requestMethod = route.request.method; if (requestMethod === "GET") { return route.fulfill({ status: 200, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ hello: "world" }), }); } return route.fulfill({ status: 200, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ hello: "again world" }), }); }); ``` ### Response #### Success Response (200) - **body** (object) - The response body, which is a JSON string. The content depends on the request method. #### Response Example For GET requests: ```json { "hello": "world" } ``` For other methods: ```json { "hello": "again world" } ``` ```