Comprehensive fetch API mocking solution for Jest testing environments with configurable responses and TypeScript support
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Functionality for mocking network failures, HTTP errors, and request aborts. Essential for testing error handling and network failure scenarios in your application.
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");
});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");
});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"
})
);
});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));
});/**
* Union type for error parameters in reject methods
*/
type ErrorOrFunction = Error | ((...args: any[]) => Promise<any>);// 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 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();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" });
});