CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-fetch-mock

Comprehensive fetch API mocking solution for Jest testing environments with configurable responses and TypeScript support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

conditional-mocking.mddocs/

Conditional Mocking

Advanced mocking capabilities that allow selective mocking based on URL patterns or custom predicates. Enables fine-grained control over which requests are mocked versus which use real fetch.

Capabilities

Is Mocking

Checks whether a given request should be mocked based on current mock conditions.

/**
 * Check if a request should be mocked based on current conditions
 * @param input - URL string or Request object to check
 * @param reqInit - Optional RequestInit for URL string inputs
 * @returns Boolean indicating if request will be mocked
 */
fetch.isMocking(input, reqInit);

Usage Examples:

// Check if URL will be mocked
const willMock = fetch.isMocking("/api/users");

// Check with Request object
const request = new Request("/api/data", { method: "POST" });
const shouldMock = fetch.isMocking(request);

// Use in conditional logic
if (fetch.isMocking("/api/critical")) {
  console.log("Critical API is being mocked");
}

Do Mock

Enables mocking for all requests, optionally with a default response.

/**
 * Enable mocking for all requests
 * @param bodyOrFunction - Optional default response body or function
 * @param init - Optional response configuration
 * @returns FetchMock instance for chaining
 */
fetch.doMock(bodyOrFunction, init);

Usage Examples:

// Enable mocking with default empty response
fetch.doMock();

// Enable mocking with default response
fetch.doMock("Default mock response");

// Enable mocking with JSON response
fetch.doMock(JSON.stringify({ mocked: true }), { 
  status: 200,
  headers: { "Content-Type": "application/json" }
});

Do Mock Once

Enables mocking for the next request only, optionally with a response.

/**
 * Enable mocking for the next request only
 * @param bodyOrFunction - Optional response body or function
 * @param init - Optional response configuration  
 * @returns FetchMock instance for chaining
 */
fetch.doMockOnce(bodyOrFunction, init);

Mock Once (Alias)

Convenient alias for doMockOnce.

/**
 * Alias for doMockOnce - enable mocking for the next request only
 * @param bodyOrFunction - Optional response body or function
 * @param init - Optional response configuration
 * @returns FetchMock instance for chaining
 */
fetch.mockOnce(bodyOrFunction, init);

Mock If

Enables mocking only for requests matching the specified URL pattern or predicate function.

/**
 * Mock requests matching URL pattern or predicate
 * @param urlOrPredicate - URL string, RegExp, or predicate function
 * @param bodyOrFunction - Optional response body or function
 * @param init - Optional response configuration
 * @returns FetchMock instance for chaining
 */
fetch.mockIf(urlOrPredicate, bodyOrFunction, init);

Do Mock If (Alias)

Alias for mockIf providing the same functionality.

/**
 * Alias for mockIf - mock requests matching URL pattern or predicate
 * @param urlOrPredicate - URL string, RegExp, or predicate function
 * @param bodyOrFunction - Optional response body or function
 * @param init - Optional response configuration
 * @returns FetchMock instance for chaining
 */
fetch.doMockIf(urlOrPredicate, bodyOrFunction, init);

Usage Examples:

// Mock specific URL
fetch.mockIf("/api/users", JSON.stringify({ users: [] }));

// Mock URLs matching regex
fetch.mockIf(/\/api\/posts\/\d+/, JSON.stringify({ post: {} }));

// Mock with predicate function
fetch.mockIf(
  (request) => request.method === "POST" && request.url.includes("/api/"),
  JSON.stringify({ success: true })
);

// Mock external APIs only
fetch.mockIf(
  (request) => request.url.startsWith("https://external-api.com"),
  (request) => {
    if (request.url.includes("/users")) {
      return Promise.resolve(JSON.stringify({ users: [] }));
    }
    return Promise.resolve(JSON.stringify({ data: "mock" }));
  }
);

Mock Once If

Enables mocking for the next request only if it matches the URL pattern or predicate.

/**
 * Mock next request if it matches URL pattern or predicate
 * @param urlOrPredicate - URL string, RegExp, or predicate function
 * @param bodyOrFunction - Optional response body or function
 * @param init - Optional response configuration
 * @returns FetchMock instance for chaining
 */
fetch.mockOnceIf(urlOrPredicate, bodyOrFunction, init);

Do Mock Once If (Alias)

Alias for mockOnceIf.

/**
 * Alias for mockOnceIf - mock next request if it matches URL pattern or predicate
 * @param urlOrPredicate - URL string, RegExp, or predicate function
 * @param bodyOrFunction - Optional response body or function
 * @param init - Optional response configuration
 * @returns FetchMock instance for chaining
 */
fetch.doMockOnceIf(urlOrPredicate, bodyOrFunction, init);

Don't Mock

Disables mocking for all requests, using real fetch instead.

/**
 * Disable mocking for all requests (use real fetch)
 * @param bodyOrFunction - Optional fallback response (typically unused)
 * @param init - Optional response configuration (typically unused)
 * @returns FetchMock instance for chaining
 */
fetch.dontMock(bodyOrFunction, init);

Usage Examples:

// Disable all mocking
fetch.dontMock();

// Use in setup to default to real fetch
beforeEach(() => {
  fetch.resetMocks();
  fetch.dontMock(); // Use real fetch unless explicitly mocked
});

Don't Mock Once

Disables mocking for the next request only, using real fetch.

/**
 * Disable mocking for the next request only (use real fetch)
 * @param bodyOrFunction - Optional fallback response (typically unused)
 * @param init - Optional response configuration (typically unused)
 * @returns FetchMock instance for chaining
 */
fetch.dontMockOnce(bodyOrFunction, init);

Don't Mock If

Disables mocking for requests matching the URL pattern or predicate, using real fetch for those requests.

/**
 * Don't mock requests matching URL pattern or predicate (use real fetch)
 * @param urlOrPredicate - URL string, RegExp, or predicate function
 * @param bodyOrFunction - Optional fallback response for non-matching requests
 * @param init - Optional response configuration for non-matching requests
 * @returns FetchMock instance for chaining
 */
fetch.dontMockIf(urlOrPredicate, bodyOrFunction, init);

Usage Examples:

// Don't mock specific internal API (use real fetch)
fetch.dontMockIf("/api/health");

// Don't mock localhost requests
fetch.dontMockIf((request) => request.url.includes("localhost"));

// Mock everything except health checks
fetch.mockResponse("Default mock");
fetch.dontMockIf(/\/health$/);

Don't Mock Once If

Disables mocking for the next request only if it matches the URL pattern or predicate.

/**
 * Don't mock next request if it matches URL pattern or predicate
 * @param urlOrPredicate - URL string, RegExp, or predicate function
 * @param bodyOrFunction - Optional fallback response for non-matching requests
 * @param init - Optional response configuration for non-matching requests
 * @returns FetchMock instance for chaining
 */
fetch.dontMockOnceIf(urlOrPredicate, bodyOrFunction, init);

Types

/**
 * Union type for URL matching parameters
 */
type UrlOrPredicate = string | RegExp | ((input: Request) => boolean);

Usage Patterns

Environment-Based Mocking

// Mock external APIs in test environment
if (process.env.NODE_ENV === "test") {
  fetch.mockIf(
    (request) => !request.url.includes("localhost"),
    "Mock response for external APIs"
  );
}

Selective API Mocking

// Mock slow/unreliable APIs, use real fetch for others
fetch.dontMock(); // Default to real fetch
fetch.mockIf(/api\.slow-service\.com/, "Fast mock response");
fetch.mockIf(/api\.unreliable\.com/, JSON.stringify({ data: [] }));

Progressive Enhancement

// Start with real fetch, add mocks as needed
beforeEach(() => {
  fetch.dontMock();
  
  // Only mock specific problematic endpoints
  fetch.mockIf("/api/flaky-endpoint", "Stable mock");
});

docs

conditional-mocking.md

error-abort-handling.md

index.md

mock-management.md

response-mocking.md

tile.json