### Install Mentoss using Bun Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Installs the Mentoss library as a development dependency using the Bun package manager. ```bash bun install mentoss -D ``` -------------------------------- ### Install Mentoss using npm Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Installs the Mentoss library as a development dependency using the npm package manager. ```bash npm install mentoss -D ``` -------------------------------- ### Install Mentoss using yarn Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Installs the Mentoss library as a development dependency using the yarn package manager. ```bash yarn add mentoss -D ``` -------------------------------- ### Install Mentoss using pnpm Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Installs the Mentoss library as a development dependency using the pnpm package manager. ```bash pnpm add mentoss -D ``` -------------------------------- ### Add a basic route to a MockServer Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Demonstrates adding a simple GET route to a MockServer instance that returns a 200 status code for the '/ping' path. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); // example route server.get("/ping", 200); ``` -------------------------------- ### Use Mentoss in a JavaScript test Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Provides a complete example of using Mentoss within a test suite, showing how to create a server and mocker, mock and unmock the global fetch, clear mocks between tests, and make a mocked fetch request. ```js import { MockServer, FetchMocker } from "mentoss"; import { expect } from "chai"; describe("My API", () => { let mocker; const server = new MockServer("https://api.example.com"); mocker = new FetchMocker({ servers: [server] }); before(() => { mocker.mockGlobal(); }); // reset the server after each test afterEach(() => { mocker.clearAll(); }); after(() => { mocker.unmockGlobal(); }); it("should return a 200 status code", async () => { // set up the route to test server.get("/ping", 200); // make the request const response = await fetch("https://api.example.com/ping"); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Create a Mentoss MockServer Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Imports the MockServer constructor from Mentoss and creates a new instance, specifying the base URL for the mock server. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); ``` -------------------------------- ### Create a Mentoss FetchMocker Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/getting-started.mdx Imports the FetchMocker constructor and creates a new instance, associating it with one or more configured MockServer instances. ```js import { MockServer, FetchMocker } from "mentoss"; const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server], }); ``` -------------------------------- ### Cloning and Installing Development Dependencies Source: https://github.com/humanwhocodes/mentoss/blob/main/README.md Commands to clone the Mentoss repository from GitHub, navigate into the directory, and install necessary development dependencies using npm. ```bash git clone https://github.com/humanwhocodes/mentoss.git cd mentoss npm install ``` -------------------------------- ### Start Local Development Server - NPM Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/README.md Starts the local development server, typically accessible at `localhost:4321`, enabling live preview and development. ```Shell npm run dev ``` -------------------------------- ### Installing Mentoss via npm Source: https://github.com/humanwhocodes/mentoss/blob/main/README.md Command to install the Mentoss library using the npm package manager. ```shell npm install mentoss ``` -------------------------------- ### Using Exported Fetch Function with Mentoss FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/creating-fetch-mocker.mdx This example shows how to extract the fetch method directly from a FetchMocker instance and use it for making mocked requests in a test. It demonstrates setting up a mock server route, using the extracted myFetch function, and asserting the response status, without affecting the global fetch. It also includes test setup and teardown using afterEach. ```javascript import { MockServer, FetchMocker } from "mentoss"; import { expect } from "chai"; describe("My API", () => { const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server], }); // extract the fetch function const myFetch = mocker.fetch; // reset the server after each test afterEach(() => { mocker.clearAll(); }); it("should return a 200 status code", async () => { // set up the route to test server.get("/ping", 200); // make the request const response = await myFetch("https://api.example.com/ping"); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Adding a GET Route with URL Parameters to MockServer (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/creating-mock-server.mdx Shows how to define a GET route using a URL pattern that includes a placeholder parameter (`:userId`). This allows the mock server to match requests to URLs like `/users/123` or `/users/456` and respond with the specified status code (200), making the mock more flexible for dynamic paths. ```JavaScript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/users/:userId", 200); ``` -------------------------------- ### Install Project Dependencies - NPM Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/README.md Installs all required project dependencies listed in the `package.json` file. ```Shell npm install ``` -------------------------------- ### Basic Mentoss Usage Example Source: https://github.com/humanwhocodes/mentoss/blob/main/README.md Demonstrates importing MockServer and FetchMocker, creating a server and mocker, defining routes, using the mocked fetch, and performing assertions and clearing. ```javascript import { MockServer, FetchMocker } from "mentoss"; // create a new server with the given base URL const server = new MockServer("https://api.example.com"); // simple mocked route server.get("/foo/bar", 200); // return specific response server.post("/foo/baz", { status: 200, body: { message: "Success" }, headers: { "Content-Type": "application/json", }, }); // match more of the request server.post( { url: "/foo/boom", headers: { "Content-type": "application/json", }, body: { test: true, }, }, 404, ); // create a mocker that uses the server const mocker = new FetchMocker({ servers: [server], }); // here's your shiny new fetch() function if you want to use it directly const { fetch } = mocker; // or overwrite the global mocker.mockGlobal(); // make a request const response = await fetch("https://api.example.example.com/foo/bar"); // check that the request was made assert(mocker.called("https://api.example.com/foo/bar")); // check that all routes were called assert(mocker.allRoutesCalled()); // clear the server to start over server.clear(); // clear everything in the mocker (including servers) mocker.clearAll(); ``` -------------------------------- ### Adding a Simple GET Route to MockServer (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/creating-mock-server.mdx Demonstrates adding a basic GET route to a `MockServer` instance. It configures the server to respond to a specific path (`/ping`) relative to the base URL with a fixed HTTP status code (200). This is the simplest way to define a mock response for a direct URL match. ```JavaScript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/ping", 200); ``` -------------------------------- ### Registering a Basic GET Route with URL Parameter - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/how-routes-work.mdx Demonstrates how to register a basic GET route using the `mentoss` MockServer. The route pattern `/api/users/:id` includes a URL parameter `:id`. This configuration matches GET requests to paths like `/api/users/123` and returns a 200 status code, ignoring any query parameters. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/api/users/:id", 200); ``` -------------------------------- ### Registering a GET Route with URL and Query Parameters - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/how-routes-work.mdx Shows how to register a GET route that requires both a URL parameter (`:id`) and a specific query parameter (`profile: 'full'`). This route will only match requests like `/api/users/123?profile=full`, demonstrating how to make route matching more specific using the `query` object. ```js server.get( { url: "/api/users/:id", query: { profile: "full", }, }, 200, ); ``` -------------------------------- ### Get Astro CLI Help - NPM Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/README.md Displays the help documentation for the Astro command-line interface, listing available commands and options. ```Shell npm run astro -- --help ``` -------------------------------- ### Defining Async Dynamic GET Response with Mentoss (JS) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This example shows how to use an `async` function as a response creator in `mentoss`. It simulates network latency by waiting for 1 second using `setTimeout` before returning the response pattern object. This is useful for testing scenarios requiring delayed responses. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/users/123", async request => { await new Promise(resolve => setTimeout(resolve, 1000)); return { status: 200, body: { id: "123", name: "Alice" } }; }); ``` -------------------------------- ### Handling Multiple Identical GET Requests with Mentoss Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/how-routes-work.mdx This snippet demonstrates how to define multiple routes with the same pattern to handle consecutive identical GET requests to a parameterized endpoint using Mentoss single-use routes. Each route definition will match one request in order. ```JavaScript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/api/users/:id", 200); server.get("/api/users/:id", 200); ``` -------------------------------- ### Set Response Body using Mentoss - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This snippet illustrates how to define a specific response body using the `body` key. The example configures a GET request to `/users` to return a 200 status and a JSON object as the response body. Mentoss automatically handles stringifying object bodies. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/users", { status: 200, body: { id: 123, name: "Alice", }, }); ``` -------------------------------- ### Setting Basic Cookies with CookieCredentials in JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx Demonstrates how to set a basic cookie using the `setCookie` method of `CookieCredentials`. Shows examples with and without a base URL, highlighting the requirement for the `domain` option when no base URL is provided. Requires `CookieCredentials` class. ```javascript // With a base URL const credentials = new CookieCredentials("https://example.com"); credentials.setCookie({ name: "sessionId", value: "abc123" }); // Without a base URL const genericCredentials = new CookieCredentials(); genericCredentials.setCookie({ name: "sessionId", value: "abc123", domain: "example.com" // domain is required when no base URL is set }); ``` -------------------------------- ### Simulating Resource State Changes with Mentoss Single-Use Routes Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/how-routes-work.mdx This snippet shows how to use single-use routes in Mentoss to simulate state changes for a specific resource, such as a user being deleted. It defines a sequence of GET, DELETE, and GET routes for the same path, each with a different expected response status code. ```JavaScript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/api/users/123", 200); server.delete("/api/users/123", 204); server.get("/api/users/123", 404); ``` -------------------------------- ### Set Response Headers using Mentoss - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This snippet shows how to include specific HTTP headers in a mock response using the `headers` key. The example simulates a redirect by setting the status to 301 and providing a `Location` header. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/redirect", { status: 301, headers: { Location: "https://example.com", }, }); ``` -------------------------------- ### Demonstrating Cookie Matching Rules with CookieCredentials in JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx Illustrates the rules by which `CookieCredentials` determines if a cookie should be included in a request. Shows examples of requests that will and will not include a secure cookie set for a specific path and domain. Requires `CookieCredentials` and `fetch`. ```javascript const credentials = new CookieCredentials("https://example.com"); // Set a secure cookie for /admin path credentials.setCookie({ name: "adminSession", value: "xyz789", path: "/admin", secure: true }); // Will include cookie (matches domain, path, and protocol) await fetch("https://example.com/admin/users"); // Won't include cookie (wrong protocol) await fetch("http://example.com/admin/users"); // Won't include cookie (wrong path) await fetch("https://example.com/user/profile"); // Will include cookie (subdomain is allowed) await fetch("https://sub.example.com/admin/users"); ``` -------------------------------- ### Integrating CookieCredentials with FetchMocker in JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx Provides a complete example demonstrating how to use `CookieCredentials` with `FetchMocker` within a test suite. Shows initialization, setting a cookie in `beforeEach`, and making an authenticated request that automatically includes the cookie. Requires `MockServer`, `FetchMocker`, and `CookieCredentials` from "mentoss". ```javascript import { MockServer, FetchMocker, CookieCredentials } from "mentoss"; const BASE_URL = "https://example.com"; describe("Authenticated API", () => { const server = new MockServer(BASE_URL); const credentials = new CookieCredentials(BASE_URL); const mocker = new FetchMocker({ servers: [server], credentials: [credentials], baseUrl: BASE_URL, }); beforeEach(() => { // Set up authentication cookie credentials.setCookie({ name: "sessionId", value: "abc123" }); }); afterEach(() => { mocker.clearAll(); }); it("should make authenticated request", async () => { server.get({ url: "/api/data", headers: { Cookie: "sessionId=abc123" } }, { status: 200, body: { message: "success" } }); const response = await mocker.fetch("/api/data"); expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Mocking Simple CORS Request with Mentoss FetchMocker (JS) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-cors-requests.mdx Demonstrates how to mock a simple cross-origin GET request using FetchMocker. It shows setting up a MockServer route that responds with the necessary Access-Control-Allow-Origin header to allow the request from the baseUrl origin. ```js import { MockServer, FetchMocker } from "mentoss"; const BASE_URL = "https://api.example.com"; describe("My API", () => { const server = new MockServer("https://www.example.com"); const mocker = new FetchMocker({ servers: [server], baseUrl: BASE_URL, }); // extract the fetch function const myFetch = mocker.fetch; it("should return a 200 status code", async () => { // set up the route to test server.get("/ping", { status: 200, headers: { "Access-Control-Allow-Origin": BASE_URL, }, body: { message: "pong" }, }); // make the request const response = await myFetch("https://www.example.com/ping"); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Mocking Relative Fetch Requests with Mentoss (JS) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx This snippet shows how to configure FetchMocker with a baseUrl to simulate browser behavior when handling relative URLs. It sets up a mock server, creates a mocker instance with the base URL, and then uses the mocked fetch function with a relative path (/ping) to test a route. It includes setup and teardown for a test suite. ```JavaScript import { MockServer, FetchMocker } from "mentoss"; import { expect } from "chai"; const BASE_URL = "https://api.example.com"; describe("My API", () => { const server = new MockServer(BASE_URL); const mocker = new FetchMocker({ servers: [server], baseUrl: BASE_URL, }); // extract the fetch function const myFetch = mocker.fetch; // reset the mocker after each test afterEach(() => { mocker.clearAll(); }); it("should return a 200 status code", async () => { // set up the route to test server.get("/ping", 200); // make the request const response = await myFetch("/ping"); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Defining Dynamic GET Response with Mentoss (JS) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This snippet demonstrates how to use a function to generate a dynamic response for a specific GET route (`/users/123`) using the `mentoss` library. The function receives the `request` object, allowing access to request details like a unique `id`, and returns a response pattern object specifying the status code and body. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/users/123", request => { console.log(`Received request: ${request.id}`); return { status: 200, body: { id: "123", name: "Alice" } }; }); ``` -------------------------------- ### Set Response Body and Headers using Mentoss - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This snippet demonstrates combining the `headers` and `body` keys in the response pattern object to set both specific headers and a specific body for a mock response. The example sets the `Content-Type` header and provides a JSON body. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/users", { status: 200, headers: { "Content-Type": "application/json", }, body: { id: 123, name: "Alice", }, }); ``` -------------------------------- ### Illustrating Route Matching Order - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/how-routes-work.mdx Demonstrates how the order of route registration affects matching. When a request like `GET /api/users/123` is made, the server matches the first registered route (`/api/users/:id`) and returns a 200 status, even though a more specific route (`/api/users/123`) is registered later. This highlights the 'first match wins' behavior. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/api/users/:id", 200); server.get("/api/users/123", 204); ``` -------------------------------- ### Delay Response using Mentoss - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This snippet shows how to introduce a delay before returning a mock response using the `delay` key. The value of `delay` is the number of milliseconds to wait. The example delays a 200 status response for 1 second. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/users", { status: 200, delay: 1000, // delay the response by 1 second }); ``` -------------------------------- ### Checking Specific Route Called with FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/testing-helpers-fetch-mocker.mdx Shows how to use the `mocker.called()` method to check if a specific route has been called. It supports checking by a simple URL string (defaulting to GET) or by a detailed request pattern object including URL, method, and body. ```js import { MockServer, FetchMocker } from "mentoss"; const server1 = new MockServer("https://api1.example.com"); const server2 = new MockServer("https://api2.example.com"); const mocker = new FetchMocker({ servers: [server1, server2] }); server1.post( { url: "/users", body: { name: "John Doe", }, }, 200, ); console.log(mocker.called("https://api1.example.com/users")); // false await mocker.fetch("https://api1.example.com/users", { method: "POST", body: { name: "John Doe", }, }); console.log(mocker.called("https://api1.example.com/users")); // true console.log(mocker.called({ url: "https://api1.example.com/users", method: "POST", body: { name: "John Doe", }, })); // true ``` -------------------------------- ### Mocking Preflighted CORS Request with Mentoss - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-cors-requests.mdx Demonstrates setting up a Mentoss mock server and fetch mocker to handle a preflighted CORS request. It shows how to define mock responses for both the OPTIONS preflight request and the subsequent GET request, and includes clearing the preflight cache after each test using `afterEach`. ```javascript import { MockServer, FetchMocker } from "mentoss"; const BASE_URL = "https://api.example.com"; describe("My API", () => { const server = new MockServer("https://www.example.com"); const mocker = new FetchMocker({ servers: [server], baseUrl: BASE_URL, }); // extract the fetch function const myFetch = mocker.fetch; // clear preflight cache entries afterEach(() => { mocker.clearPreflightCache(); }); it("should return a 200 status code", async () => { // this is for the preflight request server.options("/ping", { status: 200, headers: { "Access-Control-Allow-Origin": BASE_URL, "Access-Control-Allow-Headers": "Content-Type", }, }); // this is the route that we want to call server.get("/ping", { status: 200, headers: { "Access-Control-Allow-Origin": BASE_URL, }, body: { message: "pong" }, }); // make the request const response = await myFetch("https://www.example.com/ping", { headers: { "Content-Type": "application/json", }, }); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Matching URL with URL Parameters (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-request-patterns.mdx Shows how to define a route in mentoss that matches a GET request to a URL with a placeholder (/users/:userId) only when the value of the URL parameter (userId) matches a specific value (123). It utilizes the 'params' key in the request pattern object. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get( { url: "/users/:userId", params: { userId: "123", }, }, 200, ); ``` -------------------------------- ### Matching URL with Query Parameters (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-request-patterns.mdx Demonstrates how to define a route in mentoss that matches a GET request to a specific URL (/users) only when it includes a particular query parameter (userId) with a specific value (123). It uses the 'query' key in the request pattern object. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get( { url: "/users", query: { userId: "123", }, }, 200, ); ``` -------------------------------- ### Mocking Preflighted CORS Request with Mentoss FetchMocker (JS) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-cors-requests.mdx Illustrates mocking a preflighted cross-origin request (e.g., with custom headers like Content-Type). It shows setting up separate OPTIONS and GET routes on the MockServer, with the OPTIONS route providing the necessary Access-Control-Allow-Origin and Access-Control-Allow-Headers for the preflight check. ```js import { MockServer, FetchMocker } from "mentoss"; const BASE_URL = "https://api.example.com"; describe("My API", () => { const server = new MockServer("https://www.example.com"); const mocker = new FetchMocker({ servers: [server], baseUrl: BASE_URL, }); // extract the fetch function const myFetch = mocker.fetch; it("should return a 200 status code", async () => { // this is for the preflight request server.options("/ping", { status: 200, headers: { "Access-Control-Allow-Origin": BASE_URL, "Access-Control-Allow-Headers": "Content-Type", }, }); // this is the route that we want to call server.get("/ping", { status: 200, headers: { "Access-Control-Allow-Origin": BASE_URL, }, body: { message: "pong" }, }); // make the request const response = await myFetch("https://www.example.com/ping", { headers: { "Content-Type": "application/json", }, }); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Matching Request with Headers (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-request-patterns.mdx Illustrates how to define a route in mentoss that matches a GET request to a specific URL (/users) only when it includes a particular HTTP header (Authorization) with a specific value (Bearer token). It uses the 'headers' key in the request pattern object. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get( { url: "/users", headers: { Authorization: "Bearer token", }, }, 200, ); ``` -------------------------------- ### Mocking Preflighted CORS Request with Credentials (mentoss, JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-cors-requests.mdx This snippet demonstrates how to use the `mentoss` library to mock a server that handles a preflighted CORS request requiring credentials. It sets up a `MockServer` and `FetchMocker`, configures the mocker to handle credentials, and defines mock responses for both the `OPTIONS` (preflight) and `GET` requests to the `/ping` endpoint. It specifically shows how to include the `Access-Control-Allow-Credentials: true` header in both responses, which is crucial for allowing the browser to send and process responses for requests made with credentials. It then makes a mocked fetch request and asserts the status code. ```JavaScript import { MockServer, FetchMocker } from "mentoss"; const BASE_URL = "https://www.example.com"; const API_URL = "https://api.example.com"; describe("My API", () => { const server = new MockServer(API_URL); const cookies = new CookieCredentials(API_URL); const mocker = new FetchMocker({ servers: [server], baseUrl: BASE_URL, credentials: [cookies], }); // extract the fetch function const myFetch = mocker.fetch; it("should return a 200 status code", async () => { // this is for the preflight request server.options("/ping", { status: 200, headers: { "Access-Control-Allow-Origin": BASE_URL, "Access-Control-Allow-Headers": "Custom", "Access-Control-Allow-Credentials": "true", }, }); // this is the route that we want to call server.get("/ping", { status: 200, headers: { "Access-Control-Allow-Origin": BASE_URL, "Access-Control-Allow-Headers": "Custom", "Access-Control-Allow-Credentials": "true", }, body: { message: "pong" }, }); // make the request const response = await myFetch("https://www.example.com/ping", { headers: { Custom: "header", }, }); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Checking if a specific route is called with MockServer in JS Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/testing-helpers-mock-server.mdx The `called()` method on a `MockServer` instance checks if a specific route has been called. It accepts either a URL string (assuming GET) or a detailed request pattern object for more specific matching, using the same logic as route handling. It returns `true` if a matching call occurred, `false` otherwise. ```js import { MockServer, FetchMocker } from "mentoss"; const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server] }); server.post( { url: "/users", body: { name: "John Doe", }, }, 200, ); console.log(server.called("/users")); // false await mocker.fetch("https://api.example.com/users", { method: "POST", body: { name: "John Doe", }, }); console.log(server.called("/users")); // true console.log(server.called({ url: "/users", method: "POST", body: { name: "John Doe", }, })); // true ``` -------------------------------- ### Set Response Status Code using Mentoss - JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This snippet demonstrates how to set a specific HTTP status code for a mock response using the `status` key in the response pattern object. It shows a GET request to `/users` configured to return a 200 status code. The description also notes that for status codes only, the number can be passed directly as a shorthand. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.get("/users", { status: 200, }); ``` -------------------------------- ### Initializing a MockServer Instance in Mentoss (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/creating-mock-server.mdx Imports the `MockServer` class from the 'mentoss' library and creates a new instance. The constructor requires the base URL that the mock server will handle requests for. This sets up the foundation for defining routes. ```JavaScript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); ``` -------------------------------- ### Preview Production Build Locally - NPM Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/README.md Serves the production build locally, allowing testing of the final output before deployment. ```Shell npm run preview ``` -------------------------------- ### Initializing Mentoss FetchMocker Instance (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/creating-fetch-mocker.mdx This snippet demonstrates how to import the necessary classes from "mentoss" and create a new FetchMocker instance. It requires at least one MockServer instance to be provided in the servers array during initialization. The created mocker instance is then ready to be used for mocking fetch requests. ```javascript import { MockServer, FetchMocker } from "mentoss"; const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server], }); ``` -------------------------------- ### Build Production Site - NPM Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/README.md Builds the project for production, generating static assets and outputting the final site to the `./dist/` directory. ```Shell npm run build ``` -------------------------------- ### Configuring Jest for ESM Support Source: https://github.com/humanwhocodes/mentoss/blob/main/README.md Shows the command needed in package.json scripts to enable experimental VM modules in Node.js, allowing Jest to run ESM-only libraries like Mentoss. ```bash node --experimental-vm-modules ./node_modules/.bin/jest ``` -------------------------------- ### Project Directory Structure Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/README.md Outlines the standard directory layout for the Astro + Starlight project, showing key folders like `public`, `src`, and configuration files. ```Text .\n├── public/\n├── src/\n│ ├── assets/\n│ ├── content/\n│ │ ├── docs/\n│ └── content.config.ts\n├── astro.config.mjs\n├── package.json\n└── tsconfig.json ``` -------------------------------- ### Run Astro CLI Commands - NPM Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/README.md Executes various Astro command-line interface commands, such as adding integrations (`astro add`) or checking the project (`astro check`). ```Shell npm run astro ... ``` -------------------------------- ### Mocking Global Fetch with Mentoss FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/creating-fetch-mocker.mdx This snippet illustrates how to replace the global fetch() function with the mocked version provided by FetchMocker using mocker.mockGlobal(). It shows how to restore the original fetch using mocker.unmockGlobal() after the tests are complete. This pattern is useful for integrating mocking into existing code or test suites that rely on the global fetch. ```javascript import { MockServer, FetchMocker } from "mentoss"; import { expect } from "chai"; describe("My API", () => { let mocker; const server = new MockServer("https://api.example.com"); mocker = new FetchMocker({ servers: [server], }); // mock the global fetch function before(() => { mocker.mockGlobal(); }); // reset the server after each test afterEach(() => { mocker.clearAll(); }); // unmock the global fetch function after(() => { mocker.unmockGlobal(); }); it("should return a 200 status code", async () => { // set up the route to test server.get("/ping", 200); // make the request const response = await fetch("https://api.example.com/ping"); // check the response expect(response.status).to.equal(200); }); }); ``` -------------------------------- ### Checking All Routes Called with FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/testing-helpers-fetch-mocker.mdx Demonstrates how to use the `mocker.allRoutesCalled()` method to check if all routes configured across all mock servers have been called at least once. It shows the method returning `false` until all routes are invoked via `mocker.fetch()` and then returning `true`. ```js import { MockServer, FetchMocker } from "mentoss"; const server1 = new MockServer("https://api1.example.com"); const server2 = new MockServer("https://api2.example.com"); const mocker = new FetchMocker({ servers: [server1, server2] }); server1.get("/users", 200); server2.post("/users", 200); console.log(mocker.allRoutesCalled()); // false await mocker.fetch("https://api1.example.com/users"); console.log(mocker.allRoutesCalled()); // false await mocker.fetch("https://api2.example.com/users", { method: "POST" }); console.log(mocker.allRoutesCalled()); // true ``` -------------------------------- ### Creating CookieCredentials Instances with Mentoss (JS) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx This snippet illustrates the two ways to instantiate CookieCredentials in Mentoss: providing a base URL to associate cookies with a specific domain, or creating a generic instance without a domain, requiring domain specification for each cookie added later. ```JavaScript import { CookieCredentials } from "mentoss"; // Create credentials for a specific domain const credentials = new CookieCredentials("https://example.com"); // Or create credentials without a domain const genericCredentials = new CookieCredentials(); ``` -------------------------------- ### Clearing All Routes with FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/testing-helpers-fetch-mocker.mdx Shows how to use the `mocker.clearAll()` method to remove all routes previously configured on all servers managed by the FetchMocker instance. This is essential for resetting the mocker's state between individual tests. ```js import { MockServer, FetchMocker } from "mentoss"; const server1 = new MockServer("https://api1.example.com"); const server2 = new MockServer("https://api2.example.com"); const mocker = new FetchMocker({ servers: [server1, server2] }); server1.get("/users", 200); server2.post("/users", 200); mocker.clearAll(); await mocker.fetch("https://api1.example.com/users"); // Error! ``` -------------------------------- ### Setting Cookie Attributes with CookieCredentials in JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx Shows how to set additional attributes like `path`, `sameSite`, and `secure` when using the `setCookie` method. Explains the default values for these attributes. Requires `CookieCredentials` class. ```javascript credentials.setCookie({ name: "sessionId", value: "abc123", path: "/admin", // defaults to "/" sameSite: "none", // defaults to "lax" secure: true // defaults to false }); ``` -------------------------------- ### Mocking Fetch on Specific Objects with Mentoss FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/creating-fetch-mocker.mdx This snippet demonstrates how to use mocker.mockObject() to replace the fetch method on a specific object (myApi) instead of the global one. It also shows how to mock a property with a custom name (customFetch) and how to restore the original methods using mocker.unmockObject(). This is useful for targeted mocking within specific parts of an application. ```javascript const myApi = { fetch: globalThis.fetch, async getData() { return this.fetch("/api/data"); } }; // mock fetch only on myApi mocker.mockObject(myApi); // mock fetch with a custom property name mocker.mockObject(myApi, "customFetch"); // restore original fetch functions mocker.unmockObject(myApi); ``` -------------------------------- ### Configuring Mentoss Mock with Multiple Criteria JS Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-request-patterns.mdx Demonstrates configuring a `mentoss` mock server route to match a POST request based on a combination of criteria. The pattern specifies matching a URL with a specific parameter value (`userId`), a required header (`Content-Type`), and a specific JSON structure in the request body. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.post( { url: "/users/:userId", params: { userId: "123", }, headers: { "Content-Type": "application/json", }, body: { name: "John Doe", }, }, 200, ); ``` -------------------------------- ### Asserting All Routes Called with FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/testing-helpers-fetch-mocker.mdx Illustrates the `assertAllRoutesCalled()` method, which acts as an assertion. It throws an error if any configured route has not been called, providing a way to enforce that all expected API interactions occurred during a test. ```js import { MockServer, FetchMocker } from "mentoss"; const server1 = new MockServer("https://api1.example.com"); const server2 = new MockServer("https://api2.example.com"); const mocker = new FetchMocker({ servers: [server1, server2] }); server1.get("/users", 200); server2.post("/users", 200); await mocker.fetch("https://api1.example.com/users"); server.assertAllRoutesCalled(); // Error! ``` -------------------------------- ### Asserting all routes are called with MockServer in JS Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/testing-helpers-mock-server.mdx The `assertAllRoutesCalled()` method on a `MockServer` instance acts as an assertion. It verifies that all configured routes have been called. If any route has not been called, it throws an error containing details about the uncalled routes, making it suitable for test frameworks. ```js import { MockServer, FetchMocker } from "mentoss"; const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server] }); server.get("/users", 200); server.post("/users", 200); await mocker.fetch("https://api.example.com/users"); server.assertAllRoutesCalled(); // Error! ``` -------------------------------- ### Checking if all routes are called with MockServer in JS Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/testing-helpers-mock-server.mdx The `allRoutesCalled()` method on a `MockServer` instance checks if every configured route has been called at least once. It returns `true` if all routes have been called, and `false` otherwise. This is useful for verifying comprehensive test coverage of defined API endpoints. ```js import { MockServer, FetchMocker } from "mentoss"; const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server] }); server.get("/users", 200); server.post("/users", 200); console.log(server.allRoutesCalled()); // false await mocker.fetch("https://api.example.com/users"); console.log(server.allRoutesCalled()); // false await mocker.fetch("https://api.example.com/users", { method: "POST" }); console.log(server.allRoutesCalled()); // true ``` -------------------------------- ### Accessing Uncalled Routes with FetchMocker (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/testing-helpers-fetch-mocker.mdx Demonstrates accessing the `mocker.uncalledRoutes` property, which returns an array containing information about routes that were configured but have not yet been called. This property is useful for generating custom test failure messages or reports. ```js import { MockServer, FetchMocker } from "mentoss"; const server1 = new MockServer("https://api1.example.com"); const server2 = new MockServer("https://api2.example.com"); const mocker = new FetchMocker({ servers: [server1, server2] }); server1.get("/users", 200); server2.post("/users", 200); await mocker.fetch("https://api1.example.com/users"); console.log(mocker.uncalledRoutes); // ["🚧 [Route: POST https://api2.example.com/users -> 200]"] ``` -------------------------------- ### Clearing MockServer routes in JS Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/testing-helpers-mock-server.mdx The `clear()` method on a `MockServer` instance removes all previously configured routes. This allows the same `MockServer` instance to be reused across multiple tests with different route configurations, preventing interference between tests. After calling `clear()`, any subsequent fetch requests will fail unless new routes are added. ```js import { MockServer, FetchMocker } from "mentoss"; const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server] }); server.get("/users", 200); server.clear(); await mocker.fetch("https://api.example.com/users"); // Error! ``` -------------------------------- ### Deleting Cookies with Attributes using CookieCredentials in JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx Shows how to delete a cookie when it was originally set with `domain` or `path` attributes, emphasizing that these attributes must also be included in the `deleteCookie` call. Requires `CookieCredentials` class. ```javascript credentials.deleteCookie({ name: "sessionId", domain: "example.com", }); ``` -------------------------------- ### Matching Request with Body (JavaScript) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-request-patterns.mdx Demonstrates how to define a route in mentoss that matches a POST request to a specific URL (/users) only when the request body (treated as JSON by default) contains a specific property (name) with a specific value (John Doe). It uses the 'body' key in the request pattern object. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); server.post( { url: "/users", body: { name: "John Doe", }, }, 200, ); ``` -------------------------------- ### Accessing Request Context in Mentoss Response (JS) Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-response-patterns.mdx This snippet demonstrates how to access additional request context like cookies, URL parameters (`params`), and query string parameters (`query`) within a dynamic response function in `mentoss`. The context is provided as the second argument to the function, allowing the response to be tailored based on these request details. ```javascript import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); // Match URLs like /users/123 server.get("/users/:id", (request, { cookies, params, query }) => { // Access cookies const sessionId = cookies.get("sessionId"); // Access URL parameters const userId = params.id; // Access query string parameters const format = query.get("format") ?? "json"; return { status: 200, body: { userId, sessionId, format } }; }); ``` -------------------------------- ### Accessing uncalled routes with MockServer in JS Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/testing-helpers-mock-server.mdx The `uncalledRoutes` property on a `MockServer` instance provides an array containing information about all routes that have been configured but have not yet been called. This property is useful for programmatically checking which routes were missed during testing or for generating custom error messages. ```js import { MockServer, FetchMocker } from "mentoss"; const server = new MockServer("https://api.example.com"); const mocker = new FetchMocker({ servers: [server] }); server.get("/users", 200); server.post("/users", 200); await mocker.fetch("https://api.example.com/users"); console.log(server.uncalledRoutes); // ["🚧 [Route: POST https://api.example.com/users -> 200]"] ``` -------------------------------- ### Deleting Basic Cookies with CookieCredentials in JavaScript Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/fetch-mockers/mocking-browser-requests.mdx Illustrates how to delete a cookie using the `deleteCookie` method, specifying only the cookie name. Requires `CookieCredentials` class. ```javascript credentials.deleteCookie({ name: "sessionId", }); ``` -------------------------------- ### Configuring Mentoss Mock to Match Blob Body JS Source: https://github.com/humanwhocodes/mentoss/blob/main/docs/src/content/docs/mock-servers/extended-request-patterns.mdx Configures a `mentoss` mock server route to match a POST request that may contain a `Blob` body. It requires manually setting the `Content-Type` header and the `body` property in the mock pattern to match the expected content and type of the `Blob`, as the pattern cannot directly use a `Blob` instance. ```js import { MockServer } from "mentoss"; const server = new MockServer("https://api.example.com"); // assuming this is the blob you want to match when it is received const blob = new Blob([JSON.stringify({ name: "John Doe" })], { type: "application/json", }); server.post( { url: "/users", headers: { "Content-Type": blob.type, }, body: { name: "John Doe" } }, 200, ); ```