npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jest-vest

v1.0.6

Published

A lightweight JavaScript library for mocking multiple `fetch` responses in Jest tests. Designed to simplify and modularize the process of returning different mock responses based on the requested URL.

Downloads

343

Readme

jest-vest

A lightweight JavaScript library for mocking multiple fetch responses in Jest tests. Designed to simplify and modularize the process of returning different mock responses based on the requested URL.

Features

  • Mock multiple fetch responses based on URLs.
  • Modularize and simplify conditional checks for mock responses.
  • Type-safe and developer-friendly, with clear error handling for missing or unexpected URLs.
  • Flexible enough to handle a single response or multiple responses.

Installation

Install via npm:

npm install jest-vest

or with yarn:

yarn add jest-vest

Usage

Mocking Multiple Fetch Responses

Use mockMultiGlobalFetch to mock multiple fetch calls, each returning a predefined response for a specific URL.

import { mockMultiGlobalFetch } from "jest-vest";

describe("mockMultiGlobalFetch example", () => {
  it("mocks multiple fetch responses", async () => {
    // Arrange: Define mock responses
    const mockResponses = [
      {
        url: "https://api.example.com/user",
        response: { id: 1, name: "John Doe" },
      },
      {
        url: "https://api.example.com/posts",
        response: [{ id: 101, title: "Mocking with Jest" }],
      },
    ];

    mockMultiGlobalFetch(mockResponses);

    // Act: Fetch from mocked URLs
    const userResponse = await fetch("https://api.example.com/user");
    const userData = await userResponse.json();

    const postsResponse = await fetch("https://api.example.com/posts");
    const postsData = await postsResponse.json();

    // Assert: Verify the mocked responses
    expect(userData).toEqual({ id: 1, name: "John Doe" });
    expect(postsData).toEqual([{ id: 101, title: "Mocking with Jest" }]);
  });
});

Mocking a Single Fetch Response

If your test only needs one consistent response for all fetch calls, use mockGlobalFetch.

import { mockGlobalFetch } from "jest-vest";

describe("mockGlobalFetch example", () => {
  it("mocks a single response for all fetch requests", async () => {
    // Arrange: Define a single mock response
    const mockResponse = { success: true, message: "Mocked response" };

    mockGlobalFetch(mockResponse);

    // Act: Fetch from any URL
    const response = await fetch("https://api.example.com/test");
    const data = await response.json();

    // Assert: Verify the mocked response
    expect(data).toEqual({ success: true, message: "Mocked response" });
  });
});

API Reference

mockMultiGlobalFetch(mockSeeds: MockResponseSeed[]): void

Mocks the global fetch function with predefined responses for specific URLs.

Parameters

  • mockSeeds (MockResponseSeed[]): An array of objects containing:
    • url (string): The URL to mock.
    • response (unknown): The mock response returned when the URL is requested.

Example

mockMultiGlobalFetch([
  { url: "https://api.example.com/data", response: { data: "mocked" } },
]);

Throws

  • An error if mockSeeds is empty or fetch is called for a URL not in mockSeeds.

mockGlobalFetch<T>(mockResponse: MockResponse<T>): void

Mocks the global fetch function to return a consistent response for all requests.

Parameters

  • mockResponse (T): The mock response object to return for any fetch call.

Example

mockGlobalFetch({ status: "ok", message: "All requests are mocked." });

Error Handling

  1. No Mock Responses Provided
    If no responses are passed to mockMultiGlobalFetch, an error will be thrown:

    No mock responses were provided to mockMultiGlobalFetch.
  2. URL Not Mocked
    If fetch is called with a URL that isn't in mockSeeds, an error will be thrown:

    No mock response found for URL: https://api.example.com/unexpected.

Test Coverage

mockMultiGlobalFetch Tests

  • Handles multiple URL-specific responses.
  • Throws an error for unmocked URLs.
  • Validates the presence of at least one mock response.

mockGlobalFetch Tests

  • Returns a consistent response for all requests.
  • Handles asynchronous fetch behavior correctly.

Why Jest-Vest?

Testing React components that make multiple network requests can get messy with lots of conditional checks, especially if you don't know the exact order of the requests. jest-vest makes your tests cleaner, modular, and easier to maintain by centralizing your fetch mocking logic.


Contributing

Contributions are welcome! If you have ideas or improvements, please open an issue or submit a pull request on GitHub.


This should give you a clear, professional set of documentation that will help developers understand and use your library effectively!