{"id":16996106,"url":"https://github.com/gadicc/fetch-mock-cache","last_synced_at":"2026-04-18T16:01:22.519Z","repository":{"id":182938887,"uuid":"669399884","full_name":"gadicc/fetch-mock-cache","owner":"gadicc","description":"Caching mock fetch implementation for all JS runtimes and frameworks.","archived":false,"fork":false,"pushed_at":"2025-10-05T12:17:18.000Z","size":398,"stargazers_count":1,"open_issues_count":1,"forks_count":3,"subscribers_count":2,"default_branch":"dev","last_synced_at":"2025-10-05T12:30:16.415Z","etag":null,"topics":["bun","deno","fetch","fetch-mock","jest","mock"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/fetch-mock-cache","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gadicc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-07-22T06:40:59.000Z","updated_at":"2025-10-05T12:16:06.000Z","dependencies_parsed_at":"2024-10-14T03:51:34.971Z","dependency_job_id":null,"html_url":"https://github.com/gadicc/fetch-mock-cache","commit_stats":null,"previous_names":["gadicc/jest-fetch-mock-cache","gadicc/fetch-mock-cache"],"tags_count":9,"template":false,"template_full_name":null,"purl":"pkg:github/gadicc/fetch-mock-cache","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gadicc%2Ffetch-mock-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gadicc%2Ffetch-mock-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gadicc%2Ffetch-mock-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gadicc%2Ffetch-mock-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gadicc","download_url":"https://codeload.github.com/gadicc/fetch-mock-cache/tar.gz/refs/heads/dev","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gadicc%2Ffetch-mock-cache/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31974954,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-18T00:39:45.007Z","status":"online","status_checked_at":"2026-04-18T02:00:07.018Z","response_time":103,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bun","deno","fetch","fetch-mock","jest","mock"],"created_at":"2024-10-14T03:51:31.013Z","updated_at":"2026-04-18T16:01:22.493Z","avatar_url":"https://github.com/gadicc.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# fetch-mock-cache\n\nCaching mock fetch implementation for all runtimes and frameworks.\n\nCopyright (c) 2023 by Gadi Cohen. [MIT Licensed](./LICENSE.txt).\n\n[![NPM Version](https://img.shields.io/npm/v/fetch-mock-cache?logo=npm)](https://www.npmjs.com/package/fetch-mock-cache)\n[![JSR](https://jsr.io/badges/@gadicc/fetch-mock-cache)](https://jsr.io/@gadicc/fetch-mock-cache)\n[![JSR Score](https://jsr.io/badges/@gadicc/fetch-mock-cache/score)](https://jsr.io/@gadicc/fetch-mock-cache)\n![GitHub Workflow Status (with event)](https://img.shields.io/github/actions/workflow/status/gadicc/jest-fetch-mock-cache/release.yml)\n![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/gadicc/26d0f88b04b6883e1a6bba5b9b344fab/raw/fetch-mock-cache-lcov-coverage.json)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)\n[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)\n\n\n## 🏁 Introduction\n\n- 💡 **Tired of writing mocks?**  \n  Skip manually crafting `fetch()` mocks — just run a real `fetch()` once and auto cache the result.\n\n- ⚡ **Fast feedback loop**  \n  Cached responses make tests run *much* faster — ideal for TDD (Test Driven Development) against real APIs.\n\n- 👥 **Team \u0026 CI friendly**  \n  Commit the cache to your repo so everyone (and your CI) benefits from consistent, speedy tests.\n\n- 🔧 **Proven approach**  \n  Used by [yahoo-finance2](https://www.npmjs.com/package/yahoo-finance2) to test 1400+ API calls in \u003c 1s on every commit.\n\n- 💬 **Open to ideas**  \n  Feature requests and contributions welcome!\n\nNB: if you're still using **v1** (formerly `jest-fetch-mock-cache`),\nsee the [old README](https://github.com/gadicc/fetch-mock-cache/tree/1.x)\nand/or [MIGRATING.md](./MIGRATING.md) for how to upgrade.\n\n## Quick Start\n\nGenerally your code will look something like this, but, **see further below** for\nthe [**exact code for different runtimes and testing frameworks**](#runtimes)\n.\n\n```ts\n// Default for node runtime, see grid below for bun/deno.\nimport createFetchCache from \"fetch-mock-cache\";\n// See list of possible stores, below.\nimport Store from \"fetch-mock-cache/stores/fs\";\n\nconst fetchCache = createFetchCache({ Store });\n\ndescribe(\"cachingMock\", () =\u003e {\n  it(\"works with a JSON response\", async (t) =\u003e {\n    const url = \"http://echo.jsontest.com/key/value/one/two\";\n    const expectedResponse = { one: \"two\", key: \"value\" };\n    t.mock.method(globalThis, \"fetch\", fetchCache);\n\n    for (let i = 0; i \u003c 2; i++) {\n      const response = await fetch(url);\n      const data = await response.json();\n      const expectedCacheHeader = i === 0 ? \"MISS\" : \"HIT\";\n      expect(response.headers.get(\"X-FMC-Cache\")).toBe(expectedCacheHeader);\n      expect(data).toEqual(expectedResponse);\n    }\n  });\n});\n```\n\n- The **first** time this runs, a _real_ request will be made to\n  `jsontest.com`, and the result returned. But, it will also be\n  saved to cache.\n\n- **Subsequent requests** will return the cached copy without\n  making an HTTP request.\n\n- **Commit `tests/fixtures/http`** (default) to your repo for\n  super fast tests in the future for all contributors and CI.\n\n\u003ca name=\"runtimes\"\u003e\u003c/a\u003e\n\n## Supported runtimes and test frameworks\n\nClick on the \"Quick Start / Example\" links to see a working implementation for your framework of choice.\n\n| Runtime                         | Framework                                                          | Status                                                                                                                                                                                                                                                                                     | Quick Start / Example                                                                                                                           |\n| ------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |\n| [Node](https://nodejs.org/) 20+ | [`node:test`](https://nodejs.org/api/test.html)                    | ![Dynamic YAML Badge](https://img.shields.io/badge/dynamic/yaml?url=https%3A%2F%2Fgist.githubusercontent.com%2Fgadicc%2Ff66f0ad9395e4019ec5209719377650b%2Fraw%2Fedbb28289e9c452d4d1f482454dd02ff41a8b255%2Fresults.yaml\u0026query=%24.node.native\u0026logo=nodedotjs\u0026label=%20\u0026labelColor=%23ddd) | [direct](./tests/runtimes/node/src/native-direct-mock.spec.ts) or with [fetch-mock](./tests/runtimes/node/src/native-fetch-mock.spec.ts)        |\n|                                 | [`jest`](https://jestjs.io/)                                       | ![Dynamic YAML Badge](https://img.shields.io/badge/dynamic/yaml?url=https%3A%2F%2Fgist.githubusercontent.com%2Fgadicc%2Ff66f0ad9395e4019ec5209719377650b%2Fraw%2Fedbb28289e9c452d4d1f482454dd02ff41a8b255%2Fresults.yaml\u0026query=%24.node.jest\u0026logo=jest\u0026label=%20\u0026labelColor=%23aaa)        | [direct](./tests/runtimes/node/src/jest-direct-mock.spec.ts) or with [jest-fetch-mock](./tests/runtimes/node/src/jest-fetch-mock.spec.ts)       |\n|                                 | [`vitest`](https://vitest.dev/)                                    | ![Dynamic YAML Badge](https://img.shields.io/badge/dynamic/yaml?url=https%3A%2F%2Fgist.githubusercontent.com%2Fgadicc%2Ff66f0ad9395e4019ec5209719377650b%2Fraw%2Fedbb28289e9c452d4d1f482454dd02ff41a8b255%2Fresults.yaml\u0026query=%24.node.vitest\u0026logo=vitest\u0026label=%20\u0026labelColor=%23ddd)    | [direct](./tests/runtimes/node/src/vitest-direct-mock.spec.ts) or with [vitest-fetch-mock](./tests/runtimes/node/src/vitest-fetch-mock.spec.ts) |\n| [Deno](https://deno.com/)       | [`deno test`](https://docs.deno.com/runtime/fundamentals/testing/) | ![Dynamic YAML Badge](https://img.shields.io/badge/dynamic/yaml?url=https%3A%2F%2Fgist.githubusercontent.com%2Fgadicc%2Ff66f0ad9395e4019ec5209719377650b%2Fraw%2Fedbb28289e9c452d4d1f482454dd02ff41a8b255%2Fresults.yaml\u0026query=%24.deno.native\u0026logo=deno\u0026label=%20\u0026labelColor=%23aaa)      | [direct](./tests/runtimes/deno/src/direct-mock.test.ts)                                                                                         |\n| [Bun](https://bun.sh/)          | [`bun:test`](https://bun.sh/docs/cli/test)                         | ![Dynamic YAML Badge](https://img.shields.io/badge/dynamic/yaml?url=https%3A%2F%2Fgist.githubusercontent.com%2Fgadicc%2Ff66f0ad9395e4019ec5209719377650b%2Fraw%2Fedbb28289e9c452d4d1f482454dd02ff41a8b255%2Fresults.yaml\u0026query=%24.bun.native\u0026logo=bun\u0026label=%20\u0026labelColor=%23aaa)        | [direct](./tests/runtimes/bun/src/direct.spec.ts), maybe soon [`bun-bagel`](https://github.com/DRFR0ST/bun-bagel)                               |\n\n## What's cached\n\nSample output from the Quick Start code above, when used with `NodeFSStore`:\n\n```bash\n$ cat tests/fixtures/http/echo.jsontest.com\\!key\\!value\\!one\\!two\n```\n\n```js\n{\n  \"request\": {\n    \"url\": \"http://echo.jsontest.com/key/value/one/two\"\n  },\n  \"response\": {\n    \"ok\": true,\n    \"status\": 200,\n    \"statusText\": \"OK\",\n    \"headers\": {\n      \"access-control-allow-origin\": \"*\",\n      \"connection\": \"close\",\n      \"content-length\": \"39\",\n      \"content-type\": \"application/json\",\n      \"date\": \"Fri, 21 Jul 2023 16:59:17 GMT\",\n      \"server\": \"Google Frontend\",\n      \"x-cloud-trace-context\": \"344994371e51195ae21f236e5d7650c4\"\n    },\n    \"bodyJson\": {\n      \"one\": \"two\",\n      \"key\": \"value\"\n    }\n  }\n}\n```\n\nJSON bodies are stored as a decoded object in `bodyJSON` for increased\nreadability.  Text bodies are stored as a string in `bodyText`, and\nbinary bodies are stored as a Base64 encoded string in `bodyBase64`.\n\n## Debugging\n\nWe use [debug](https://www.npmjs.com/package/debug) for debugging. E.g.:\n\n```bash\n$ DEBUG=fetch-mock-cache:* yarn test\nyarn run v1.22.19\n$ jest\n  fetch-mock-cache:core Fetching and caching 'http://echo.jsontest.com/key/value/one/two' +0ms\n  fetch-mock-cache:core Using cached copy of 'http://echo.jsontest.com/key/value/one/two' +177ms\n PASS  src/index.spec.ts\n  cachingMock\n    ✓ should work (180 ms)\n```\n\n## Available Stores\n\n- [`stores/fs`](./src/stores/fs.ts) - use your runtime's FileSystem API to\n  store cached requests to the filesystem, for persistance. These can be\n  committed to your projects repository / source control for faster future\n  testing, including for CI.\n\n- [`stores/memory`](./src/stores/memory.ts) - keep the cache in memory.\n  The cache will not persist and will be created again from scratch each\n  time you run your code.\n\n### Create your own Store\n\nSee also the [`store`](./src/store.ts) \"root\" class. Don't instantiate\ndirectly; rather extend this class overriding at least `fetchContent` and\n`storeContent`, and perhaps, `idFromRequest`, the constructor and others\naccording to your needs. Here's an example to combine with a database:\n\n```ts\nimport FMCStore from \"fetch-mock-cache/store\";\nimport type { FMCCacheContent, FMCStoreOptions } from \"fetch-mock-cache/store\";\nimport db from \"./db\"; // your existing db\n\nexport default class MyStore extends FMCStore {\n  async fetchContent(req: FMCCacheContent[\"request\"]) {\n    const _id = await this.idFromRequest(request);\n    return (await db.collection(\"fmc\").findOne({ _id })).content;\n  }\n  async storeContent(content: FMCCacheContent) {\n    const _id = await this.idFromRequest(content.request);\n    await db.collection(\"jfmc\").insertOne({ _id, content });\n  }\n}\n```\n\n## Overriding the Default Caching Behaviour\n\n### Passing options to be used for the next `fetch()` call\n\n```ts\n// These will be used for the next fetch call ONCE only.  However, `once()`\n// may be called multiple times to queue options for multiple future calls.\nfetchCache.once({\n  /* options */\n});\n```\n\n### Manually specifying an ID\n\nGenerally we don't need to think about cache IDs, as we can reliably\ngenerate them from the `Request` object (e.g. based on URL and hashes\nof the headers, body, etc.).\n\nBut sometimes, we may want to specify this manually, e.g.\n\n1. **We'd rather use the _test name_** as the id, vs something URL-based.\n2. **It can't be reliably generated**, e.g. formData with a random boundary.\n\nIn this case, we can:\n\n```ts\nfetchCache.once({ id: \"mytest\" });\nfetch(/* ... */); // or code that uses fetch();\n```\n\nMake sure the `id` is relevant for your store. e.g. if using the fs store,\nmake sure `id` is a valid file name (the fs store will still append `.json`\nat the end).\n\n### Manually controlling cache behaviour\n\nYou can also pass the following to `fetchCache.once`:\n\n```ts\n{\n  id?: string; // as above\n  /** True (default): use cached response if available; false: always fetch from network.\n   * You can also provide a promise or function that returns a boolean or promise.\n   */\n  readCache?:\n    | boolean\n    | Promise\u003cboolean\u003e\n    | ((...args: Parameters\u003cFMCStore[\"fetchContent\"]\u003e) =\u003e Promise\u003cboolean\u003e);\n  /** If a fetch was performed, should we write it to the cache?  Can be a boolean, a\n   * promise, or a function that returns a boolean or promise.  In the case of a promise,\n   * the write will open occur when the promise resolves, and AFTER the response is\n   * returned.  This allows for more complex patterns, where e.g. you could rely on the\n   * further processing of the response in other functions before deciding whether to\n   * cache it or not, but does require some extra care.\n   */\n  writeCache?:\n    | boolean\n    | Promise\u003cboolean\u003e\n    | ((...args: Parameters\u003cFMCStore[\"storeContent\"]\u003e) =\u003e Promise\u003cboolean\u003e);\n}\n```\n\nSee below in Tips \u0026 Tricks on how you can leverage this to conditionally replace the\ncache for failing tests.\n\n\n## Internal and Experimental Features\n\nInternal and experimental features are generally prefixed by an underscore (\"`_`\").\nYou're welcome to use them, however, they are not part of our API contract - as such,\nthey may change or disappear at any time, _without following semantic versioning_.\n\nOften these are used for new ideas that are still in development, where, we'd like\nyou to have easy access to them (and appreciate your feedback!), but, they're not\n(yet) considered stable.\n\nCurrent experiments:\n\nNone.\n\nPrevious experiments:\n\n*  `_once()` has been promoted to `_once()` after a long, succesful testing period.\n\n## Tips \u0026 Tricks\n\n### Rewrite the cache only for failing tests.\n\n1. Let's wrap the `it()` function to allow a callback after the test\n\n   ```ts\n   import { it as _it } from \"...\"; // your fave library\n\n   export const it = function wrappedIt(\n     suite: string,\n     fn: (\n       t: Parameters\u003ctypeof _it\u003e[0],\n       onFinish: (cb: (error?: unknown) =\u003e void | Promise\u003cvoid\u003e) =\u003e void,\n     ) =\u003e void | Promise\u003cvoid\u003e,\n   ) {\n     const finishCallbacks = [] as Array\u003c(error?: unknown) =\u003e void\u003e;\n\n     const onFinish = (cb: (error?: unknown) =\u003e void) =\u003e {\n       finishCallbacks.push(cb);\n     };\n\n     const finish = (error?: unknown) =\u003e {\n       for (const cb of finishCallbacks) {\n         cb(error);\n       }\n     };\n\n     const wrappedFn = (t: Deno.TestContext) =\u003e {\n       let result: ReturnType\u003ctypeof fn\u003e;\n       try {\n         result = fn(t, onFinish);\n       } catch (error) {\n         finish(error);\n         throw error;\n       }\n\n       if (result === undefined) {\n         finish();\n         return undefined;\n       }\n\n       if (result instanceof Promise) {\n         return result.then(finish).catch((error) =\u003e {\n           finish(error);\n           throw error;\n         });\n       }\n\n       throw new Error(\n         `Test \"${name}\" failed with unexpected result: ${result}`,\n       );\n     };\n\n     _it(suite, wrappedFn);\n   };\n   ```\n\n2. Now do something like this:\n\n   ```ts\n   import { it } from \"above\";\n   import fetchCache from \"wherever-you-set-it-up\";\n\n   function conditionalCache(onFinish) {\n     if (process.env.FETCH_CACHE === \"recache\")\n       // i.e. if the test fails and has an error, then `writeCache` resolves to \"true\"\n       fetchCache.once({ readCache: false, writeCache: onFinish.then(error =\u003e !!error)})\n   }\n\n   it(\"rewrites the cache on fail\", async(_t, onFinish) =\u003e {\n     conditionalCache(onFinish);\n     const response = await fetch(...);\n     const result = await response.json();\n     expect(result).toMatch({\n       success: true\n     });\n   })\n   ```\n\n3. Now, by default, we'll use the cache as normal. However, if you set\n   `FETCH_CACHE=\"recache\"`, we won't use the cache, and if the test fails,\n   we'll replace the cached result.\n\n   This is super useful for testing if API response (and not your code)\n   has changed, commit the new responses, and then adapt your code as\n   necessary. You'd only do this after first making sure all your existing\n   tests are passing.\n\n## TODO\n\n- [x] Cache request headers too and hash them in filename / key / id.\n- [ ] Browser-environment support. Please open an issue if you need this, and in what cases. jsdom?\n- [ ] Handle and store invalid JSON too?\n\n```\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgadicc%2Ffetch-mock-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgadicc%2Ffetch-mock-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgadicc%2Ffetch-mock-cache/lists"}