### Install @fetch-mock/vitest Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/vitest.md Install the package as a development dependency. ```shell npm i -D @fetch-mock/vitest ``` -------------------------------- ### Installation Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Instructions on how to install fetch-mock and its integration packages for Jest and Vitest. ```APIDOC ## Installation Install fetch-mock as a dev dependency. ```bash npm install --save-dev fetch-mock # For Jest integration npm install --save-dev @fetch-mock/jest # For Vitest integration npm install --save-dev @fetch-mock/vitest # Deno (using npm: prefix) import fetchMock from 'npm:fetch-mock@12.3.0'; ``` ``` -------------------------------- ### Install fetch-mock and related packages Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Install fetch-mock as a dev dependency. Use specific packages for Jest and Vitest integration. Deno installations use the npm: prefix. ```bash npm install --save-dev fetch-mock # For Jest integration npm install --save-dev @fetch-mock/jest # For Vitest integration npm install --save-dev @fetch-mock/vitest # Deno (using npm: prefix) import fetchMock from 'npm:fetch-mock@12.3.0'; ``` -------------------------------- ### End-to-end example with route and API call Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md A complete example showing how to set up a specific route with headers and then make a call to a hypothetical API function, asserting the expected response status. ```javascript fetchMock.route('begin:http://it.at.here/api', 403).route( { url: 'begin:http://it.at.here/api', headers: { authorization: 'Basic dummy-token', }, }, 200, ); callApi('/endpoint', 'dummy-token').then((res) => { expect(res.status).to.equal(200); }); ``` -------------------------------- ### Install fetch-mock with npm Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/installation.md Install fetch-mock as a development dependency using npm. ```bash npm install --save-dev fetch-mock ``` -------------------------------- ### Start Local Development Server Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/README.md Starts a local development server that reflects changes live without requiring a restart. ```bash $ yarn start ``` -------------------------------- ### Install Codemods and Dependencies Source: https://github.com/wheresrhys/fetch-mock/blob/main/packages/codemods/README.md Install the codemod tool, jscodeshift, and the target fetch-mock version. ```bash npm i -D @fetch-mock/codemods jscodeshift fetch-mock@12 ``` -------------------------------- ### Setup Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/vitest.md Import and optionally hook fetchMock into vitest's global mock management. ```APIDOC ## Setup ```js import fetchMock, { manageFetchMockGlobally } from '@fetch-mock/vitest'; manageFetchMockGlobally(); // optional ``` ``` -------------------------------- ### Mock Fetch with Options and Delay Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/quickstart.md Mock a specific GET request to 'http://httpbin.org/my-url', returning a JSON object. This example also demonstrates faking a slow network with a delay and matching requests based on specific headers. ```javascript fetchMock.mockGlobal().get( 'http://httpbin.org/my-url', { hello: 'world' }, { delay: 1000, // fake a slow network headers: { user: 'me', }, }, ); ``` -------------------------------- ### Install @fetch-mock/jest Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/jest.md Install the package as a development dependency using npm. ```shell npm i -D @fetch-mock/jest ``` -------------------------------- ### Install Dependencies Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/README.md Installs project dependencies using Yarn. ```bash $ yarn ``` -------------------------------- ### Manual Adjustments Example for sandbox() Source: https://github.com/wheresrhys/fetch-mock/blob/main/packages/codemods/README.md Illustrates manual modifications required when using the `.sandbox()` method, particularly after codemod execution. ```javascript // Before const fm = require('fetch-mock').sandbox(); // After const fm = require('fetch-mock'); // ... // If mocking global fetch, you will also need to call .mockGlobal() at least once per test suite. // e.g. in a beforeAll/beforeEach block: // fm.mockGlobal(); ``` -------------------------------- ### Setup fetch-mock with vitest Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/vitest.md Import and optionally hook fetchMock into vitest's global mock management. ```javascript import fetchMock, { manageFetchMockGlobally } from '@fetch-mock/vitest'; manageFetchMockGlobally(); // optional ``` -------------------------------- ### Mock a GET request with express-style routing Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/index.md Mock requests using express-style routing with parameters. This example demonstrates mocking a user data fetch and verifying the call history. ```javascript import fetchMock from 'fetch-mock'; fetchMock .mockGlobal() .route({ express: '/api/users/:user', expressParams: {user: 'kenneth'} }, { userData: { email: 'kenneth@example.com' } }, 'userDataFetch'); const res = await fetch('http://example.com/api/users/kenneth'); assert(fetchMock.callHistory.called('userDataFetch')) const data = await res.json(); assertEqual(data.userData.email, 'kenneth@example.com') ``` -------------------------------- ### Node.js Example: Mocking Fetch in a Request Function Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/quickstart.md This example shows how to mock the global fetch in a Node.js environment to test a function that makes an asynchronous request. It includes mocking the fetch call, awaiting the result, and then unmocking the global fetch. ```javascript export async function makeRequest() { const res = await fetch('http://example.com/my-url', { headers: { user: 'me', }, }); return res.json(); } ``` ```javascript import { makeRequest } from './make-request'; import fetchMock from 'fetch-mock'; // Mock the fetch() global to return a response fetchMock.mockGlobal().get( 'http://httpbin.org/my-url', { hello: 'world' }, { delay: 1000, // fake a slow network headers: { user: 'me', }, }, ); const data = await makeRequest(); console.log('got data', data); // Unmock fetchMock.unmockGlobal(); ``` -------------------------------- ### Mocking fetch with @fetch-mock/core Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/blog/2024-07-21-introducing-core.md This example demonstrates how to use @fetch-mock/core to mock global fetch. Note that @fetch-mock/core separates the fetch handler from the mocking methods. ```javascript import fetchMock from 'fetch-mock'; // Instead of fetchMock.sandbox(), use fetchMock.fetchHandler jest.mock(global, 'fetch', () => fetchMock.fetchHandler); // Mock a specific route fetchMock.mock('http://my.site', 200); ``` -------------------------------- ### Set Global Configuration Option Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/configuration.md Set global configuration options directly on the `fetchMock.config` object. This example disables partial body matching. ```javascript const fetchMock = require('fetch-mock'); fetchMock.config.matchPartialBody = false; ``` -------------------------------- ### HTTP Method Shorthands (.get(), .post(), etc.) Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Provides convenient shorthands for creating routes that specifically match a given HTTP method (e.g., GET, POST, PUT, DELETE, HEAD, PATCH). ```APIDOC ## .get(matcher, response, options) ## .post(matcher, response, options) ## .put(matcher, response, options) ## .delete(matcher, response, options) ## .head(matcher, response, options) ## .patch(matcher, response, options) ### Description Shorthands for `mock()` that create routes that only respond to requests using a particular http method. ### Example ```javascript fetchMock.get('/api/users', { users: ['Alice', 'Bob'] }); fetchMock.post('/api/users', { status: 201, body: { id: 1 } }); ``` ``` -------------------------------- ### Mock a simple GET request Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/index.md Use this to mock a basic GET request to a specific URL and assert that the response is okay. ```javascript import fetchMock from 'fetch-mock'; fetchMock.mockGlobal().route('http://example.com', 200); const res = await fetch('http://example.com'); assert(res.ok); ``` -------------------------------- ### Setup fetch-mock with Jest Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/jest.md Import fetchMock and optionally manageFetchMockGlobally to integrate with Jest's global mock management. This allows Jest's clearAllMocks, resetAllMocks, and restoreAllMocks to control fetchMock. ```javascript import fetchMock, { manageFetchMockGlobally } from '@fetch-mock/jest'; import { jest } from '@jest/globals'; manageFetchMockGlobally(jest); // optional ``` -------------------------------- ### Mocking Global Fetch in Jest with @fetch-mock/core Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/blog/2024-07-20-new-beginnings.md Demonstrates how to use the @fetch-mock/core library to mock the global fetch API within a Jest test environment. This setup allows for testing fetch requests using fetch-mock's routing capabilities. ```javascript import fetchMock from '@fetch-mock/core' jest.mock(global, 'fetch', fetchMock.fetchHandler) it('works just fine', () => { fetchMock.route('http://here.com', 200) await expect (fetch('http://here.com')).resolves }) ``` -------------------------------- ### Define custom HTTP method shorthands Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md You can easily define your own shorthand methods for less common HTTP methods by extending the fetchMock instance. This example shows how to add a .purge() shorthand. ```javascript fetchMock.purge = function (matcher, response, options) { return this.mock( matcher, response, Object.assign({}, options, { method: 'PURGE' }), ); }; ``` -------------------------------- ### JSDOM Compatibility Setup Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/jest.md To ensure compatibility with JSDOM, you can either use a specific jest-environment-jsdom package or extend the default jest-environment-jsdom to include Request, Response, and ReadableStream globals. ```javascript import { TestEnvironment } from 'jest-environment-jsdom'; export default class CustomTestEnvironment extends TestEnvironment { await setup() { await super.setup(); this.global.Request = Request; this.global.Response = Response; this.global.ReadableStream = ReadableStream; } } ``` -------------------------------- ### Dynamic Response Based on Request Headers (Function with Request Object) Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/response.md Another example of a dynamic response function, this time accessing headers via the request object's get method. It returns 200 if the Authorization header is present, otherwise 403. ```javascript ({request}) => request.headers.get('Authorization') ? 200 : 403 ``` -------------------------------- ### Create and Inspect a New fetch-mock Instance Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/resetting.md Demonstrates creating a new, independent fetch-mock instance and inspecting its routes and call history. This can be an alternative to removing and clearing routes on an existing instance. ```javascript fetchMock.route('http://my.site', 200); fetchMock.fetchHandler('http://my.site'); const newFM = fetchMock.createInstance(); newFM.routes.routes; // Array[1] newFM.callHistory.calls(); // Array[0] ``` -------------------------------- ### Build Static Website Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/README.md Generates static website content into the 'build' directory, ready for hosting. ```bash $ yarn build ``` -------------------------------- ### Deploy Website (SSH) Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/README.md Deploys the website using SSH. Assumes SSH is configured for deployment. ```bash $ USE_SSH=true yarn deploy ``` -------------------------------- ### Import fetch-mock in Deno Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/installation.md Import fetch-mock in Deno environments using the 'npm:' prefix. Specify the version for reliable imports. ```javascript import fetchMock from 'npm:fetch-mock@12.3.0'; ``` -------------------------------- ### .anyOnce() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Creates a route that responds to a single fetch request. This method is a combination of `.any()` and `.once()`. ```APIDOC ## .anyOnce(response, options) ### Description Creates a route that responds to any single request. ### Parameters #### Response - **response**: The response to return for the single fetch request. #### Options - **options**: Optional configuration for the route. ### Example ```javascript fetchMock.anyOnce('/api/resource', { status: 201 }); ``` ``` -------------------------------- ### .any() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md A shorthand for `mock()` that creates a route that will respond to any fetch request. It accepts a response and optional configuration options. ```APIDOC ## .any(response, options) ### Description Shorthand for `mock()` which creates a route that will return a response to any fetch request. ### Parameters #### Response - **response**: The response to return for any fetch request. #### Options - **options**: Optional configuration for the route. ### Example ```javascript fetchMock.any('/api/data', { data: 'some data' }); ``` ``` -------------------------------- ### HTTP Method Once Shorthands (.getOnce(), .postOnce(), etc.) Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Similar to the HTTP method shorthands, these methods create routes that match a specific HTTP method but can only be called once. ```APIDOC ## .getOnce(matcher, response, options) ## .postOnce(matcher, response, options) ## .putOnce(matcher, response, options) ## .deleteOnce(matcher, response, options) ## .headOnce(matcher, response, options) ## .patchOnce(matcher, response, options) ### Description Creates a route that only responds to a single request using a particular http method. ### Example ```javascript fetchMock.getOnce('/api/resource/1', { data: 'specific data' }); ``` ``` -------------------------------- ### Scoped fetchMock Expect Extensions Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/vitest.md Assert specific HTTP methods by replacing 'Fetched' with the HTTP verb. For example, use 'toHaveDeleted' to check for DELETE requests. ```javascript expect(fetchMock).toHaveDeleted('http://example.com/user/1') ``` -------------------------------- ### Implement removed convenience methods Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/upgrade-guide.md Methods like getOnce() and getAnyOnce() have been removed. Replicate their behavior using the repeat option. ```javascript fetchMock.get(url, response, { repeat: 1 }) fetchMock.get('*', response, { repeat: 1 }) ``` -------------------------------- ### Add a custom matcher for request validation Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Use .addMatcher() to integrate reusable custom matchers into fetch-mock. This example demonstrates an 'isAuthorized' matcher that checks request headers based on a boolean input. ```javascript fetchMock .addMatcher({ name: 'isAuthorized', matcher: ({ isAuthorized }) => (url, options) => { const actuallyIsAuthorized = options.headers && options.headers.auth; return isAuthorized ? actuallyIsAuthorized : !actuallyIsAuthorized; }, }) .mock({ isAuthorized: true }, 200) .mock({ isAuthorized: false }, 401); ``` -------------------------------- ### Mock a single request with .anyOnce() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Use .anyOnce() to create a route that responds to only a single fetch request, regardless of its method or URL. This is useful for one-off request mocks. ```javascript fetchMock.anyOnce('response for a single request'); ``` -------------------------------- ### Create HTTP method-specific routes Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Shorthand methods like .get(), .post(), .put(), .delete(), .head(), and .patch() create routes that only respond to requests using a specific HTTP method. This improves clarity and reduces configuration complexity. ```javascript fetchMock.get('/users', [{ id: 1, name: 'Alice' }]); fetchMock.post('/users', { status: 201 }); ``` -------------------------------- ### Dynamic Response Based on Request Headers (Function) Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/response.md Use a function to dynamically determine the response based on request details. This example returns a 200 status if an Authorization header is present, otherwise 403. ```javascript ({url, options}) => options.headers.Authorization ? 200 : 403 ``` -------------------------------- ### Deploy Website (No SSH) Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/README.md Deploys the website without using SSH. Requires specifying the GitHub username. ```bash $ GIT_USER= yarn deploy ``` -------------------------------- ### Define Multiple Fetch Routes Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/quickstart.md Set up multiple fetch routes with different HTTP methods, URLs, responses, and names. These methods are chainable for concise route definition. ```javascript fetchMock .get('http://good.com/', 200, 'good get') .post('http://good.com/', 400, 'good post') .get('http://bad.com/', 500, 'bad get'); ``` -------------------------------- ### Create single-request HTTP method shorthands Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Methods like .getOnce(), .postOnce(), .putOnce(), .deleteOnce(), .headOnce(), and .patchOnce() create routes that respond to only a single request using a specific HTTP method. This is useful for ensuring a particular request is made only once. ```javascript fetchMock.getOnce('/resource', { body: 'single resource' }); ``` -------------------------------- ### Refactor node-fetch to fetch-mock Source: https://github.com/wheresrhys/fetch-mock/blob/main/packages/codemods/README.md This snippet shows the 'before' state of code using node-fetch directly. It demonstrates how to mock node-fetch using fetch-mock's sandbox. ```javascript jest.mock('node-fetch', () => require('fetch-mock').sandbox()); const nodeFetch = require('node-fetch'); it('runs a test', () => { nodeFetch.get('http://a.com', 200); myAPI.call(); expect(nodeFetch.called()).toBe(true); }); ``` -------------------------------- ### Configure Mock Responses with Various Types Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Demonstrates configuring mock responses using different types such as status codes, strings, JSON objects, full response objects, redirects, network errors, Promises, and functions. Use this for simulating diverse API behaviors. ```javascript import fetchMock from 'fetch-mock'; fetchMock.mockGlobal() // Status code .route('http://example.com/a', 404) // Plain string body (200 status) .route('http://example.com/b', 'Hello') // Object → serialized as JSON, Content-Type: application/json .route('http://example.com/c', { id: 1, name: 'Widget' }) // Full response config object .route('http://example.com/d', { status: 201, body: { created: true }, headers: { 'X-Request-Id': 'abc-123' }, }) // Simulated redirect .route('http://example.com/e', { status: 301, redirectUrl: 'http://example.com/new-location', }) // Throw a network error .route('http://example.com/f', { throws: new TypeError('Network failure') }) // Promise-based response (e.g. simulating latency) .route('http://example.com/g', new Promise((res) => setTimeout(() => res(200), 100))) // Function response — inspect the request to decide the reply .route('http://example.com/h', ({ options }) => options.headers?.Authorization ? { data: 'secret' } : 401 ); // Using a real Response instance fetchMock.route( 'http://example.com/i', new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'Content-Type': 'application/json' }, }) ); fetchMock.hardReset(); ``` -------------------------------- ### Shorthand Routing Methods for HTTP Verbs Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Utilize shorthand methods like `.get()`, `.post()`, `.put()`, `.delete()`, `.patch()`, `.getOnce()`, `.anyOnce()`, `.any()`, `.sticky()`, and `.catch()` for simplified route configuration. These methods pre-fill HTTP methods or provide fallback behavior. ```javascript import fetchMock from 'fetch-mock'; fetchMock .mockGlobal() // HTTP-method shorthands .get('http://api.example.com/items', [{ id: 1 }]) .post('http://api.example.com/items', { id: 2 }, 'create-item') .put('http://api.example.com/items/1', { id: 1, updated: true }) .delete('http://api.example.com/items/1', 204) .patch('http://api.example.com/items/1', { patched: true }) // Respond to any single GET then fall through .getOnce('http://api.example.com/banner', { message: 'Welcome!' }) // Match any URL exactly once .anyOnce(503, 'single-failure') // Match absolutely any URL (catch-all route) .any({ status: 200, body: 'default response' }) // Sticky: survives removeRoutes() calls .sticky(/config-hub.com/, { featureFlags: { darkMode: true } }) // Fallback for all unmatched requests .catch(200); // Once-only method variant fetchMock.once('http://api.example.com/token', { token: 'xyz' }, { method: 'POST' }); const res = await fetch('http://api.example.com/items'); const data = await res.json(); console.log(data); // [{ id: 1 }] fetchMock.hardReset(); ``` -------------------------------- ### Chaining route() calls Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md Demonstrates how to chain multiple route() calls to define several distinct fetch handlers in a single statement. This is useful for setting up multiple mock responses sequentially. ```javascript fetchMock.route('a', 200).route('b', 301) ``` -------------------------------- ### String matchers for routes Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md Shows various ways to define string-based matchers for URLs, including exact matches, prefix matching ('begin:'), suffix matching ('end:'), path matching ('path:'), and wildcard matching ('*'). ```javascript fetchMock .route('http://it.at.here/route', 200) .route('begin:http://it', 200) .route('end:here/route', 200) .route('path:/route', 200) .route('*', 200); ``` -------------------------------- ### Configure Custom Fetch Implementations Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/configuration.md Integrate custom fetch implementations like `node-fetch` by assigning their components to `fetchMock.config`. This allows mocking non-standard fetch environments. ```javascript import { default as fetch, Headers, Request, Response } from 'node-fetch'; import fetchMock from 'fetch-mock'; fetchMock.config = Object.assign(fetchMock.config, { Request, Response, Headers, fetch, }); ``` -------------------------------- ### Mock any fetch request with .any() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md The .any() method is a shorthand for .mock() that creates a route that will respond to any fetch request made. It accepts a response and optional options. ```javascript fetchMock.any('some response'); ``` -------------------------------- ### Defining similar routes with differing options Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md Illustrates how to define routes that share a common URL pattern but differ in specific options like headers. This is achieved by merging matchers and options objects. ```javascript fetchMock .route('http://my.site', 401) .route('http://my.site', 200, { headers: { auth: true } }); ``` -------------------------------- ### Vitest Integration with @fetch-mock/vitest Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Integrates fetch-mock with Vitest for idiomatic lifecycle methods and expect matchers. Use `manageFetchMockGlobally` in `vitest.setup.js` to link Vitest's mock management functions to fetch-mock. ```javascript // vitest.setup.js import fetchMock, { manageFetchMockGlobally } from '@fetch-mock/vitest'; manageFetchMockGlobally(); // vi.clearAllMocks() → fetchMock.mockClear() // vi.resetAllMocks() → fetchMock.mockReset() // vi.restoreAllMocks() → fetchMock.mockRestore() // vi.unstubAllGlobals() → fetchMock.mockRestore() // In a test file: import { describe, test, expect, beforeEach, afterEach } from 'vitest'; import fetchMock from '@fetch-mock/vitest'; describe('API client', () => { beforeEach(() => fetchMock.mockGlobal()); afterEach(() => fetchMock.mockRestore()); test('fetches and deletes a resource', async () => { fetchMock .get('http://api.example.com/items/5', { id: 5, name: 'Widget' }, 'get-item') .delete('http://api.example.com/items/5', 204, 'delete-item'); const getRes = await fetch('http://api.example.com/items/5'); expect(getRes.status).toBe(200); await fetch('http://api.example.com/items/5', { method: 'DELETE' }); expect(fetchMock).toHaveGot('http://api.example.com/items/5'); expect(fetchMock).toHaveDeleted('http://api.example.com/items/5'); expect(fetchMock).not.toHavePosted('http://api.example.com/items/5'); expect(fetchMock).toBeDone('delete-item'); }); }); ``` -------------------------------- ### Single options object for route configuration Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md Demonstrates using a single options object as the first parameter to route(), which can contain URL matchers, repeat counts, and response configurations. ```javascript fetchMock.route({ url: 'http://my.site', repeat: 2, response: 200 }) ``` -------------------------------- ### .sticky() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Creates a persistent route that remains active even after calls to restore(), reset(), or resetbehavior(). Ideal for setting up essential fixtures that should always be in place. ```APIDOC ## .sticky(matcher, response, options) ### Description Shorthand for `mock()` which creates a route that persists even when `restore()`, `reset()` or `resetbehavior()` are called. ### Example ```javascript fetchMock.sticky(/config-hub.com/, require('./fixtures/start-up-config.json')); ``` ``` -------------------------------- ### Configuring Mock Responses Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Demonstrates how to configure mock responses for different scenarios including status codes, string bodies, JSON objects, full response configurations, redirects, network errors, promise-based responses, and function responses. ```APIDOC ## .route(matcher, response, [options]) ### Description Configures a mock route with a specific response. ### Method fetchMock.route() ### Parameters - **matcher** (string | RegExp | Function | Array): The URL or pattern to match. - **response** (number | string | object | Response | Promise | Function): The mock response configuration. - **options** (object, optional): Additional options for the route. ### Response Types - **Status code**: e.g., `404` - **String body**: e.g., `'Hello'` - **Plain object**: e.g., `{ id: 1, name: 'Widget' }` (serialized as JSON) - **Full response config object**: e.g., `{ status: 201, body: { created: true }, headers: { 'X-Request-Id': 'abc-123' } }` - **Simulated redirect**: e.g., `{ status: 301, redirectUrl: 'http://example.com/new-location' }` - **Throw a network error**: e.g., `{ throws: new TypeError('Network failure') }` - **Promise-based response**: e.g., `new Promise((res) => setTimeout(() => res(200), 100))` - **Function response**: e.g., `({ options }) => options.headers?.Authorization ? { data: 'secret' } : 401` - **Real Response instance**: e.g., `new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'Content-Type': 'application/json' } })` ### Request Example ```javascript import fetchMock from 'fetch-mock'; fetchMock.mockGlobal() .route('http://example.com/a', 404) .route('http://example.com/c', { id: 1, name: 'Widget' }) .route('http://example.com/d', { status: 201, body: { created: true }, headers: { 'X-Request-Id': 'abc-123' }, }) .route('http://example.com/f', { throws: new TypeError('Network failure') }); ``` ``` -------------------------------- ### Import fetch-mock in ES Modules Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/installation.md Import fetch-mock using ES module syntax. This is the standard way to import modules in modern JavaScript environments. ```javascript import fetchMock from 'fetch-mock'; ``` -------------------------------- ### Import fetch-mock in CommonJS Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/installation.md Import fetch-mock using CommonJS syntax. This is typically used in Node.js environments that do not support ES modules natively. ```javascript const fetchMock = require('fetch-mock'); ``` -------------------------------- ### Mock local node-fetch instance Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/upgrade-guide.md The sandbox() method has been removed. If you need to mock a local instance of node-fetch, use the fetchHandler property. ```javascript fetchMock.fetchHandler ``` -------------------------------- ### Configure Global fetch-mock Settings Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Modify `fetchMock.config` properties to control default behavior for all routes. Options include enabling relative URLs, partial body matching, disabling Content-Length headers, and specifying a custom fetch implementation. ```javascript import fetchMock from 'fetch-mock'; // Allow relative URLs in Node.js (normally unsupported) fetchMock.config.allowRelativeUrls = true; // Globally enable partial body matching fetchMock.config.matchPartialBody = true; // Disable automatic Content-Length header on responses fetchMock.config.includeContentLength = false; // Use a custom fetch implementation (e.g. node-fetch) import nodeFetch, { Headers, Request, Response } from 'node-fetch'; Object.assign(fetchMock.config, { fetch: nodeFetch, Headers, Request, Response }); // Per-route override of a global config option fetchMock.route('http://api.example.com/upload', 200, { includeContentLength: false }); ``` -------------------------------- ### .catch() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md Specifies how to respond to fetch calls that do not match any defined routes. If no argument is provided, unmatched calls will receive a 200 response. ```APIDOC ## .catch(response) ### Description Specifies how to respond to calls to `fetch` that don't match any routes. ### Parameters #### Response - **response**: Any response compatible with `.route()`. ### Example ```javascript fetchMock.catch(200); fetchMock.catch({ status: 404, body: 'not found' }); ``` ``` -------------------------------- ### Response Instance Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/response.md Return a Response instance unaltered. ```APIDOC ## Response Instance ### Description Return a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response) instance to return unaltered. ### Method Not applicable (this describes a return value type) ### Endpoint Not applicable ### Response #### Success Response (200) - **Response** (Response) - The Response instance provided. ``` -------------------------------- ### Reset fetch-mock State Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Use these methods to clear call history, remove routes, or perform a full reset of the mock state between tests. `createInstance` allows for isolated mock environments. ```javascript import fetchMock from 'fetch-mock'; fetchMock .mockGlobal() .sticky('http://api.example.com/config', { theme: 'dark' }, 'app-config') .route('http://api.example.com/data', { items: [] }, 'get-data'); await fetch('http://api.example.com/data'); // Clear only call history (routes remain) fetchMock.clearHistory(); console.log(fetchMock.callHistory.calls().length); // 0 // Remove non-sticky routes (sticky 'app-config' survives) fetchMock.removeRoutes(); // fetchMock.removeRoutes({ names: ['get-data'] }); // remove by name // fetchMock.removeRoutes({ includeSticky: true }); // remove all incl. sticky // fetchMock.removeRoutes({ includeFallback: true }); // also remove .catch() route // Full reset: removes all routes, clears history, unmocks global fetch fetchMock.hardReset(); // fetchMock.hardReset({ includeSticky: true }); // also remove sticky routes // Create an isolated independent instance fetchMock.route('http://api.example.com/shared', 200); const sandboxed = fetchMock.createInstance(); // sandboxed inherits routes but has empty call history console.log(sandboxed.callHistory.calls().length); // 0 sandboxed.hardReset(); // only affects sandboxed instance ``` -------------------------------- ### .createInstance() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/resetting.md Creates a new, independent instance of fetch-mock. Useful for isolation or forking previous instances. ```APIDOC ## .createInstance() ### Description Can be used to create a standalone instance of fetch mock that is completely independent of other instances. It can also be used as an alternative to `fetchMock.removeRoutes().clearHistory()` by creating a completely new fetchMock instance and swapping this for the previously used one. It can also be used to "fork" a previous instance as routes are cloned from one instance to another. However call history is always reset for new instances. ### Example ```js fetchMock.route('http://my.site', 200); fetchMock.fetchHandler('http://my.site'); const newFM = fetchMock.createInstance(); newFM.routes.routes; // Array[1] newFM.callHistory.calls(); // Array[0] ``` ``` -------------------------------- ### Mock Global Fetch Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/quickstart.md Replace the global fetch implementation with fetch-mock's version to enable mocking. ```javascript fetchMock.mockGlobal(); ``` -------------------------------- ### Inspecting Recorded Calls with `fetchMock.callHistory` Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Explains how to use `fetchMock.callHistory` to inspect and filter recorded requests, check call counts, and manage the history. ```APIDOC ## `fetchMock.callHistory` — Inspecting recorded calls ### Description `fetchMock.callHistory` records every request routed through `fetchHandler` and provides methods for inspecting these calls. ### Methods - **`.called(matcher)`**: Checks if a named route was called. - **`.calls(matcher?)`**: Retrieves all recorded calls, optionally filtered by a matcher. - **`.lastCall(matcher)`**: Retrieves the last call to a named route. - **`.done(matcher)`**: Checks if expected call counts (from `repeat` option) are satisfied. - **`.flush(waitBodyParsing?)`**: Waits for all pending fetch-mock responses to settle. ### Parameters for `.calls()` - **matcher** (string | RegExp | Function | boolean, optional): Filters calls by route name, URL matcher, `true` for matched calls, or `false` for unmatched calls. ### Request Example ```javascript import fetchMock from 'fetch-mock'; fetchMock .mockGlobal() .get('http://api.example.com/users', [{ id: 1 }], 'get-users'); await fetch('http://api.example.com/users'); console.log(fetchMock.callHistory.called('get-users')); // true const last = fetchMock.callHistory.lastCall('get-users'); console.log(last.url); // 'http://api.example.com/users' await fetchMock.callHistory.flush(); ``` ``` -------------------------------- ### URL matching patterns in fetch-mock Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Fetch Mock offers various URL matching patterns for flexible request matching, including wildcards, prefixes, suffixes, substrings, hosts, paths, globs, regular expressions, and Express-style routes. It also supports matching based on query parameters, request body, headers, and custom functions. ```javascript import fetchMock from 'fetch-mock'; fetchMock.mockGlobal() // Exact URL .route('http://example.com/exact', 200) // Wildcard: match any URL .route('*', 200) // Prefix match .route('begin:http://api.example.com', 200) // Suffix match .route('end:.json', 200) // Substring match .route('include:/api/v2/', 200) // Host match .route('host:cdn.example.com', 200) // Path match (any host) .route('path:/health', 200) // Glob pattern .route('glob:http://api.example.com/*/details', 200) // Regular expression .route(///articles/\d+/, 200) // Express route with captured params .route('express:/products/:category/:id', 200) // Combined matcher object (URL prefix + POST method + required header) .route( { url: 'begin:http://api.example.com', method: 'POST', headers: { Authorization: 'Bearer token123' }, }, 201, 'authorized-post' ) // Query parameter matching .route({ url: 'http://api.example.com/search', query: { q: 'cats', page: '1' } }, { results: [] }) // Body matching (partial) .route( { url: 'http://api.example.com/login', body: { username: 'alice' }, matchPartialBody: true }, { token: 'abc123' } ) // Custom function matcher .route( (url, opts) => url.includes('/admin') && !!opts.headers?.Authorization, 200, 'admin-authorized' ); fetchMock.hardReset(); ``` -------------------------------- ### Global Configuration: fetchMock.config Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Configuration properties on `fetchMock.config` that control default behaviour across all routes, such as allowing relative URLs or enabling partial body matching. ```APIDOC ## `fetchMock.config` — Global configuration Configuration properties on `fetchMock.config` that control default behaviour across all routes. ```js import fetchMock from 'fetch-mock'; // Allow relative URLs in Node.js (normally unsupported) fetchMock.config.allowRelativeUrls = true; // Globally enable partial body matching fetchMock.config.matchPartialBody = true; // Disable automatic Content-Length header on responses fetchMock.config.includeContentLength = false; // Use a custom fetch implementation (e.g. node-fetch) import nodeFetch, { Headers, Request, Response } from 'node-fetch'; Object.assign(fetchMock.config, { fetch: nodeFetch, Headers, Request, Response }); // Per-route override of a global config option fetchMock.route('http://api.example.com/upload', 200, { includeContentLength: false }); ``` ``` -------------------------------- ### String Response Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/response.md Return a 200 Response with a string body. ```APIDOC ## String ### Description Returns a 200 `Response` with the string as the response body e.g. `"..." ### Method Not applicable (this describes a return value type) ### Endpoint Not applicable ### Response #### Success Response (200) - **Response** (Response) - A 200 Response with the string as the body. ``` -------------------------------- ### Refactor node-fetch to fetch-mock (After) Source: https://github.com/wheresrhys/fetch-mock/blob/main/packages/codemods/README.md This snippet shows the 'after' state of code after refactoring to use fetch-mock. It includes configuration for Response, Request, and Headers classes if your application uses them directly. ```javascript const fetchMock = require('fetch-mock'); jest.mock('node-fetch', () => { const nodeFetch = jest.requireActual('node-fetch'); // only needed if your application makes use of Response, Request // or Headers classes directly Object.assign(fetchMock.config, { fetch: nodeFetch, Response: nodeFetch.Response, Request: nodeFetch.Request, Headers: nodeFetch.Headers, }); return fetchMock.fetchHandler; }); const nodeFetch = require('node-fetch'); it('runs a test', () => { fetchMock.get('http://a.com', 200); myAPI.call(); expect(fetchMock.called()).toBe(true); }); ``` -------------------------------- ### Run Codemod on Project Source: https://github.com/wheresrhys/fetch-mock/blob/main/packages/codemods/README.md Execute the codemod over your entire project or specific files/directories. Avoid using the --parser option as the codemod forces the TSX parser. ```bash jscodeshift -t node_modules/@fetch-mock/codemods/src/index.js --ignore-pattern="node_modules/**/*" . ``` -------------------------------- ### route(matcher, response, options) — Define a mock route Source: https://context7.com/wheresrhys/fetch-mock/llms.txt The core routing method. Adds a route that matches requests and returns the configured response. Returns the `fetchMock` instance for chaining. ```APIDOC ## `fetchMock.route(matcher, response, options)` — Define a mock route The core routing method. Adds a route that matches requests and returns the configured response. Returns the `fetchMock` instance for chaining. The third parameter can be either an options object or a plain string used as the route name. ```js import fetchMock from 'fetch-mock'; fetchMock.mockGlobal() // Exact URL → JSON body (Content-Type: application/json set automatically) .route('http://api.example.com/posts', { posts: [] }, 'list-posts') // Match by HTTP method and URL prefix → status code only .route({ url: 'begin:http://api.example.com/posts/', method: 'DELETE' }, 204, 'delete-post') // Express-style path with param constraint .route( { url: 'express:/users/:id', params: { id: '42' } }, { id: 42, name: 'Bob' }, 'get-user-42' ) // Respond with an error (causes fetch to reject) .route('http://api.example.com/broken', { throws: new TypeError('Failed to fetch') }) // Delayed response .route('http://api.example.com/slow', 200, { delay: 500 }) // Respond only once, then fall through .route('http://api.example.com/one-time', 201, { repeat: 1 }); const res = await fetch('http://api.example.com/posts'); console.log(res.status); // 200 const body = await res.json(); console.log(body); // { posts: [] } fetchMock.hardReset(); ``` ``` -------------------------------- ### fetchMock Methods Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/wrappers/vitest.md The fetchMock instance provides methods for managing mock history and routes. ```APIDOC ## fetchMock (default export) An instance of [fetch-mock](/fetch-mock/docs/), with the following methods added: ### fetchMock.mockClear() Clears all call history from the mocked `fetch` implementation. ### fetchMock.mockReset() `fetchMock.mockReset({includeSticky: boolean})` Clears all call history from the mocked `fetch` implementation _and_ removes all routes (including fallback routes defined using `.spy()` or `.catch()`) with the exception of sticky routes. To remove these, pass in the `includeSticky: true` option. For more fine grained control over fallback routes and named routes please use `fetchMock.removeRoutes()` ### fetchMock.mockRestore() `fetchMock.mockRestore({includeSticky: boolean})` Calls `mockReset()` and additionally restores global fetch to its unmocked implementation. ``` -------------------------------- ### Replace .mock() with .route() and .mockGlobal() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/Usage/upgrade-guide.md The .mock() method has been removed. Use .route() to define a mock and .mockGlobal() to enable it. ```javascript fetchMock.route(url, response) fetchMock.mockGlobal() ``` -------------------------------- ### URL matchers — Flexible request matching Source: https://context7.com/wheresrhys/fetch-mock/llms.txt Fetch Mock provides a rich set of URL-matching patterns usable as the first argument to `.route()` or combined in a matcher object. ```APIDOC ## URL matchers — Flexible request matching Fetch Mock provides a rich set of URL-matching patterns usable as the first argument to `.route()` or combined in a matcher object. ```js import fetchMock from 'fetch-mock'; fetchMock.mockGlobal() // Exact URL .route('http://example.com/exact', 200) // Wildcard: match any URL .route('*', 200) // Prefix match .route('begin:http://api.example.com', 200) // Suffix match .route('end:.json', 200) // Substring match .route('include:/api/v2/', 200) // Host match .route('host:cdn.example.com', 200) // Path match (any host) .route('path:/health', 200) // Glob pattern .route('glob:http://api.example.com/*/details', 200) // Regular expression .route(///articles/\d+/, 200) // Express route with captured params .route('express:/products/:category/:id', 200) // Combined matcher object (URL prefix + POST method + required header) .route( { url: 'begin:http://api.example.com', method: 'POST', headers: { Authorization: 'Bearer token123' }, }, 201, 'authorized-post' ) // Query parameter matching .route({ url: 'http://api.example.com/search', query: { q: 'cats', page: '1' } }, { results: [] }) // Body matching (partial) .route( { url: 'http://api.example.com/login', body: { username: 'alice' }, matchPartialBody: true }, { token: 'abc123' } ) // Custom function matcher .route( (url, opts) => url.includes('/admin') && !!opts.headers?.Authorization, 200, 'admin-authorized' ); fetchMock.hardReset(); ``` ``` -------------------------------- ### Various response types for routes Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md Illustrates the different types of responses that can be configured for a route, including strings, status codes, objects, Promises, and dynamically generated responses using functions. ```javascript fetchMock .route('*', 'ok') .route('*', 404) .route('*', {results: []}) .route('*', {throws: new Error('Bad kitty')}) .route('*', new Promise(res => setTimeout(res, 1000, 404))) .route('*', (url, opts) => { status: 302, headers: { Location: url.replace(/^http/, 'https') }, })) ``` -------------------------------- ### Complex matchers for routes Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md Demonstrates using regular expressions, functions, and object-based matchers (including express-style routing with params) to define sophisticated criteria for handling fetch requests. ```javascript fetchMock .route(/.*\.here.*/, 200) .route((url, opts) => opts.method === 'patch', 200) .route('express:/:type/:id', 200, { params: { type: 'shoe', }, }) .route( { headers: { Authorization: 'Bearer 123' }, method: 'POST', }, 200, ); ``` -------------------------------- ### .once() Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/more-routing-methods.md A shorthand for `mock()` that creates a route that can only mock a single request. This is equivalent to using the `repeat: 1` option with `.mock()`. ```APIDOC ## .once(matcher, response, options) ### Description Shorthand for `mock()` which creates a route that can only mock a single request. ### Example ```javascript fetchMock.once('/api/users', { users: [] }); ``` ``` -------------------------------- ### Route with name as third parameter Source: https://github.com/wheresrhys/fetch-mock/blob/main/docs/docs/API/route/index.md Shows how to assign a name to a route by passing a string as the third argument to route(). This is equivalent to providing an options object with a 'name' property. ```javascript fetchMock.route('*', 200, 'catch-all') ```