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

error-abort-handling.mddocs/

Error and Abort Handling

Functionality for mocking network failures, HTTP errors, and request aborts. Essential for testing error handling and network failure scenarios in your application.

Capabilities

Mock Reject

Makes fetch calls reject with a specified error or custom error function. Used to simulate network failures or other request errors.

/**
 * Mock all fetch calls to reject with specified error
 * @param errorOrFunction - Error object, string, or function that returns a promise rejection
 * @returns FetchMock instance for chaining
 */
fetch.mockReject(errorOrFunction);

Usage Examples:

// Simple error string
fetch.mockReject("Network error");

// Error object
fetch.mockReject(new Error("Connection failed"));

// Custom error function
fetch.mockReject(() => Promise.reject(new TypeError("Failed to fetch")));

// In a test
it("handles network errors", async () => {
  fetch.mockReject("Network failure");
  
  await expect(fetch("/api/data")).rejects.toThrow("Network failure");
});

Mock Reject Once

Makes the next fetch call reject with a specified error. Subsequent calls will use default behavior or other configured mocks.

/**
 * Mock the next fetch call to reject with specified error
 * @param errorOrFunction - Error object, string, or function that returns a promise rejection  
 * @returns FetchMock instance for chaining
 */
fetch.mockRejectOnce(errorOrFunction);

Usage Examples:

// Single rejection followed by normal mock
fetch.mockRejectOnce("First call fails");
fetch.mockResponse("Second call succeeds");

// Test retry logic
it("retries on failure", async () => {
  fetch
    .mockRejectOnce("First attempt fails")
    .mockResponseOnce("Success on retry");
    
  // Your retry logic here
  const result = await retryableFetch("/api/data");
  expect(result).toBe("Success on retry");
});

Mock Abort

Makes all fetch calls throw a DOMException with name "AbortError", simulating an aborted request.

/**
 * Mock all fetch calls to abort (throw DOMException AbortError)
 * @returns FetchMock instance for chaining
 */
fetch.mockAbort();

Usage Examples:

// Mock all requests to abort
fetch.mockAbort();

// Test abort handling
it("handles aborted requests", async () => {
  fetch.mockAbort();
  
  await expect(fetch("/api/data")).rejects.toThrow(
    expect.objectContaining({
      name: "AbortError"
    })
  );
});

Mock Abort Once

Makes the next fetch call throw a DOMException with name "AbortError". Subsequent calls will use default behavior.

/**
 * Mock the next fetch call to abort (throw DOMException AbortError)
 * @returns FetchMock instance for chaining
 */
fetch.mockAbortOnce();

Usage Examples:

// Single abort followed by normal response
fetch.mockAbortOnce();
fetch.mockResponse("Success after abort");

// Test abort controller integration
it("respects abort signals", async () => {
  const controller = new AbortController();
  
  // Mock abort for explicit signal
  fetch.mockAbortOnce();
  
  await expect(
    fetch("/api/data", { signal: controller.signal })
  ).rejects.toThrow(expect.any(DOMException));
});

Types

/**
 * Union type for error parameters in reject methods
 */
type ErrorOrFunction = Error | ((...args: any[]) => Promise<any>);

Error Patterns

Network Failures

// Simulate connection timeout
fetch.mockReject(new Error("ETIMEDOUT"));

// Simulate DNS resolution failure  
fetch.mockReject(new Error("ENOTFOUND"));

// Simulate connection refused
fetch.mockReject(new Error("ECONNREFUSED"));

HTTP Errors vs Network Errors

// HTTP error (still resolves, check response.ok)
fetch.mockResponse("Not Found", { status: 404 });

// Network error (promise rejects)
fetch.mockReject("Network failure");

// Abort error (promise rejects with DOMException)
fetch.mockAbort();

Testing Error Recovery

it("recovers from transient failures", async () => {
  // First call fails, second succeeds
  fetch
    .mockRejectOnce("Temporary failure")
    .mockResponseOnce(JSON.stringify({ data: "success" }));
    
  // Test your retry logic
  const result = await fetchWithRetry("/api/data");
  expect(JSON.parse(result)).toEqual({ data: "success" });
});

docs

conditional-mocking.md

error-abort-handling.md

index.md

mock-management.md

response-mocking.md

tile.json