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

mock-management.mddocs/

Mock Management

Utilities for managing mock state, resetting mocks between tests, and controlling global mocking behavior. Essential for maintaining clean test environments and proper Jest integration.

Capabilities

Reset Mocks

Resets all mock state including call history, implementations, and returns to default mocking behavior.

/**
 * Reset all mock state and return to default behavior
 * @returns void
 */
fetch.resetMocks();

Usage Examples:

// Reset between tests
beforeEach(() => {
  fetch.resetMocks();
});

// Reset during a test
it("handles multiple scenarios", () => {
  fetch.mockResponse("First scenario");
  // ... test first scenario
  
  fetch.resetMocks();
  fetch.mockResponse("Second scenario");
  // ... test second scenario
});

// Check what resetMocks does:
// - Clears fetch.mock.calls
// - Clears fetch.mock.results  
// - Resets to default mockImplementation
// - Re-enables mocking (calls doMock())

Enable Mocks

Enables fetch mocking globally by replacing the global fetch with the mock version.

/**
 * Enable fetch mocking globally (replace global fetch with mock)
 * @returns void
 */
fetch.enableMocks();

Usage Examples:

// In setupJest.js or test setup file
require("jest-fetch-mock").enableMocks();

// Or using the alias
const { enableFetchMocks } = require("jest-fetch-mock");
enableFetchMocks();

// What enableMocks does:
// - Sets global.fetch = fetchMock
// - Sets global.fetchMock = fetchMock
// - Attempts to mock 'node-fetch' module for Node.js compatibility

Enable Fetch Mocks (Alias)

Convenient alias for enableMocks providing the same functionality.

/**
 * Alias for enableMocks - enable fetch mocking globally
 * @returns void
 */
fetch.enableFetchMocks();

Disable Mocks

Disables fetch mocking globally by restoring the original fetch implementation.

/**
 * Disable fetch mocking globally (restore original fetch)
 * @returns void
 */
fetch.disableMocks();

Usage Examples:

// Temporarily disable mocking for integration tests
beforeAll(() => {
  fetch.disableMocks();
});

afterAll(() => {
  fetch.enableMocks();
});

// What disableMocks does:
// - Restores global.fetch to original implementation (cross-fetch)
// - Stops mocking 'node-fetch' module

Disable Fetch Mocks (Alias)

Convenient alias for disableMocks.

/**
 * Alias for disableMocks - disable fetch mocking globally  
 * @returns void
 */
fetch.disableFetchMocks();

Named Export Functions

These functions are available as named exports for ES6 import syntax and provide the same functionality as the methods above.

Enable Fetch Mocks (Named Export)

/**
 * Enable fetch mocking globally (named export function)
 * @returns void
 */
function enableFetchMocks();

Usage Examples:

// ES6 import syntax
import { enableFetchMocks } from "jest-fetch-mock";

// Enable in setup
enableFetchMocks();

Disable Fetch Mocks (Named Export)

/**
 * Disable fetch mocking globally (named export function)
 * @returns void
 */
function disableFetchMocks();

Usage Examples:

// ES6 import syntax
import { disableFetchMocks } from "jest-fetch-mock";

// Disable when needed
disableFetchMocks();

Jest Integration

Setup Patterns

Option 1: Global Setup (setupJest.js)

// setupJest.js
require("jest-fetch-mock").enableMocks();

// Or with ES6
import { enableFetchMocks } from "jest-fetch-mock";
enableFetchMocks();

Option 2: Per-Test File Setup

// At top of test file
import fetchMock from "jest-fetch-mock";
fetchMock.enableMocks();

beforeEach(() => {
  fetchMock.resetMocks();
});

Option 3: Default Disabled

// setupJest.js - available but not enabled by default
require("jest-fetch-mock").enableMocks();
fetchMock.dontMock(); // Use real fetch by default

// In specific tests, enable as needed
beforeEach(() => {
  fetchMock.doMock();
});

Jest Configuration

{
  "jest": {
    "automock": false,
    "setupFiles": ["./setupJest.js"]
  }
}

Mock Inspection

Since fetchMock is a Jest mock function, you have access to all Jest mock properties:

// Call history
expect(fetch.mock.calls).toHaveLength(2);
expect(fetch.mock.calls[0][0]).toBe("/api/users");
expect(fetch.mock.calls[1][0]).toBe("/api/posts");

// Call arguments
const [url, options] = fetch.mock.calls[0];
expect(url).toBe("/api/data");
expect(options.method).toBe("POST");

// Results
expect(fetch.mock.results[0].type).toBe("return");

// Mock instance properties
expect(fetch.mock.instances).toHaveLength(2);

Best Practices

Test Isolation

describe("API tests", () => {
  beforeEach(() => {
    fetch.resetMocks(); // Clean slate for each test
  });
  
  afterEach(() => {
    // Optional: additional cleanup
    expect(fetch.mock.calls).toBeDefined();
  });
});

Environment-Specific Setup

// setupJest.js
if (process.env.NODE_ENV === "test") {
  require("jest-fetch-mock").enableMocks();
  
  // Default to mocking unless explicitly disabled
  global.fetch.doMock();
}

Integration Test Support

// For integration tests that need real fetch
const originalFetch = global.fetch;

beforeAll(() => {
  if (process.env.INTEGRATION_TESTS) {
    fetch.disableMocks();
  }
});

afterAll(() => {
  if (process.env.INTEGRATION_TESTS) {
    fetch.enableMocks();
  }
});

docs

conditional-mocking.md

error-abort-handling.md

index.md

mock-management.md

response-mocking.md

tile.json