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

fetch-mock-cache

v2.0.2

Published

Caching mock fetch implementation for all runtimes and frameworks.

Downloads

166

Readme

fetch-mock-cache

Caching mock fetch implementation for all runtimes and frameworks.

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

npm 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.

| Runtime | Framework | Status | Quick Start / Example | | ------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | Node 20+ | node:test | Dynamic YAML Badge | direct or with fetch-mock | | | jest | Dynamic YAML Badge | direct or with jest-fetch-mock | | | vitest | Dynamic YAML Badge | direct or with vitest-fetch-mock | | Deno | deno test | Dynamic YAML Badge | direct | | Bun | bun:test | Dynamic YAML Badge | direct, 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

import createCachingMock from "fetch-mock-cache";

// Use Node's FS API to store as (creating paths as necessary)
// `${process.cwd()}/tests/fixtures/${filenamifyUrl(url)}`.
// https://github.com/sindresorhus/filenamify-url
import FMCNodeFSStore from "./stores/nodeFs";
const fileCacheMock = createCachingMock({ store: new FMCNodeFSStore() });
fetchMock.mockImplementationOnce(fileCacheMock);
// To override the store location, init with store with e.g.:
// new JFMCNodeFSStore({ location: "tests/other/location" })

// Keep in memory
import FMCMemoryStore from "./stores/memory";
const memoryCacheMock = createCachingMock({ store: new JSMCMemoryStore() });
fetchMock.mockImplementationOnce(memoryCacheMock);

Create your own Store

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

class MyCustomStore extends FMCStore {
  async fetchContent(
    request: FMCCacheContent["request"],
  ): Promise<FMCCacheContent | undefined> {
    const key = await this.idFromRequest(request);
    return (await db.collection("fmc").findOne({ _id: key })).content;
  }

  async storeContent(content: FMCCacheContent): Promise<void> {
    const key = await this.idFromRequest(content.request);
    await db.collection("jfmc").insertOne({ _id: key, content });
  }
}

export default MyCustomStore;

TODO

  • [x] 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?