Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fetch-mock-cache

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fetch-mock-cache

Caching mock fetch implementation for all runtimes and frameworks.

  • 2.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

fetch-mock-cache

Caching mock fetch implementation for all runtimes and frameworks.

Copyright (c) 2023 by Gadi Cohen. MIT Licensed.

NPM Version JSR JSR Score GitHub Workflow Status (with event) Coverage semantic-release TypeScript MIT License

Introduction

Instead of individually handcrafting a mock for each and every fetch() call in your code, maybe you'd like to perform a real fetch() once, cache the result, and use that cache result for future calls. Super useful for TDD against existing APIs!!

Note: This README refer to v3 which is in active development. v2 (CommonJS & Node/Jest only, see old README) is more stable but is no longer being worked on. See MIGRATING.md for how to upgrade. v3 works but you may want to wait a bit before any serious use. Feature requests welcome!

Quick Start

Generally your code will look something like this, but, see further below for the exact code for different runtimes and testing frameworks.

import createFetchCache from "fetch-mock-cache";
// See list of possible stores, below.
import Store from "fetch-mock-cache/lib/stores/fs";

const fetchCache = createFetchCache({ Store });

describe("cachingMock", () => {
  it("works with a JSON response", async (t) => {
    const url = "http://echo.jsontest.com/key/value/one/two";
    const expectedResponse = { one: "two", key: "value" };
    t.mock.method(globalThis, "fetch", fetchCache);

    for (let i = 0; i < 2; i++) {
      const response = await fetch(url);
      const data = await response.json();
      const expectedCacheHeader = i === 0 ? "MISS" : "HIT";
      expect(response.headers.get("X-FMC-Cache")).toBe(expectedCacheHeader);
      expect(data).toEqual(expectedResponse);
    }
  });
});
  • The first time this runs, a real request will be made to jsontest.com, and the result returned. But, it will also be saved to cache.

  • Subsequent requests will return the cached copy without making an HTTP request.

  • Commit tests/fixtures/http (default) to your repo for super fast tests in the future for all contributors and CI.

Supported runtimes and test frameworks

Click on the "Quick Start / Example" links to see a working implementation for your framework of choice.

RuntimeFrameworkStatusQuick Start / Example
Node 20+node:testDynamic YAML Badgedirect or with fetch-mock
jestDynamic YAML Badgedirect or with jest-fetch-mock
vitestDynamic YAML Badgedirect or with vitest-fetch-mock
Denodeno testDynamic YAML Badgedirect
Bunbun:testDynamic YAML Badgedirect, maybe soon bun-bagel

What's cached

Sample output from the Quick Start code above, when used with NodeFSStore:

$ cat tests/fixtures/http/echo.jsontest.com\!key\!value\!one\!two
{
  "request": {
    "url": "http://echo.jsontest.com/key/value/one/two"
  },
  "response": {
    "ok": true,
    "status": 200,
    "statusText": "OK",
    "headers": {
      "access-control-allow-origin": "*",
      "connection": "close",
      "content-length": "39",
      "content-type": "application/json",
      "date": "Fri, 21 Jul 2023 16:59:17 GMT",
      "server": "Google Frontend",
      "x-cloud-trace-context": "344994371e51195ae21f236e5d7650c4"
    },
    "bodyJson": {
      "one": "two",
      "key": "value"
    }
  }
}

For non-JSON bodies, a bodyText is stored as a string. We store an object as bodyJson for readability reasons.

Debugging

We use debug for debugging. E.g.:

$ DEBUG=fetch-mock-cache:* yarn test
yarn run v1.22.19
$ jest
  fetch-mock-cache:core Fetching and caching 'http://echo.jsontest.com/key/value/one/two' +0ms
  fetch-mock-cache:core Using cached copy of 'http://echo.jsontest.com/key/value/one/two' +177ms
 PASS  src/index.spec.ts
  cachingMock
    ✓ should work (180 ms)

Available Stores

  • stores/fs - use your runtime's FileSystem API to store cached requests to the filesystem, for persistance. These can be committed to your projects repository / source control for faster future testing, including for CI.

  • stores/memory - keep the cache in memory. The cache will not persist and will be created again from scratch each time you run your code.

Create your own Store

See also the store "root" class. Don't instantiate directly; rather extend this class overriding at least fetchContent and storeContent, and perhaps, idFromRequest, the constructor and others according to your needs. Here's an example to combine with a database:

import FMCStore from "fetch-mock-cache/store";
import type { FMCCacheContent, FMCStoreOptions } from "fetch-mock-cache/store";
import db from "./db"; // your existing db

export default class MyStore extends FMCStore {
  async fetchContent(req: FMCCacheContent["request"]) {
    const _id = await this.idFromRequest(request);
    return (await db.collection("fmc").findOne({ _id })).content;
  }
  async storeContent(content: FMCCacheContent) {
    const _id = await this.idFromRequest(content.request);
    await db.collection("jfmc").insertOne({ _id, content });
  }
}

Internal and Experimental Features

Internal and experimental features are generally prefixed by an underscore ("_"). You're welcome to use them, however, they are not part of our API contract - as such, they may change or disappear at any time, without following semantic versioning.

Often these are used for new ideas that are still in development, where, we'd like you to have easy access to them (and appreciate your feedback!), but, they're not (yet) considered stable.

Current experiments:

Passing options to be used for the next fetch call

// These will be used for the next fetch call ONCE only.  However, `_once()`
// may be called multiple times to queue options for multiple future calls.
fetchCache._once({
  /* options */
});

Manually specifying an ID

Generally we don't need to think about cache IDs, as we can reliably generate them from the Request object (e.g. based on URL and hashes of the headers, body, etc.).

But sometimes, we may want to specify this manually, e.g.

  1. We'd rather use the test name as the id, vs something URL-based.
  2. It can't be reliably generated, e.g. formData with a random boundary.

In this case, we can:

fetchCache._once({ id: "mytest" });
fetch(/* ... */); // or code that uses fetch();

Make sure the id is relevant for your store. e.g. if using the fs store, make sure id is a valid file name (the fs store will still append .json at the end).

TODO

  • Cache request headers too and hash them in filename / key / id.
  • Browser-environment support. Please open an issue if you need this, and in what cases. jsdom?
  • Handle and store invalid JSON too?

Keywords

FAQs

Package last updated on 26 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc