Gathering detailed insights and metrics for jest-fetch-mock-cache
Gathering detailed insights and metrics for jest-fetch-mock-cache
Gathering detailed insights and metrics for jest-fetch-mock-cache
Gathering detailed insights and metrics for jest-fetch-mock-cache
Caching mock fetch implementation for all JS runtimes and frameworks.
npm install jest-fetch-mock-cache
54.6
Supply Chain
98.3
Quality
76.6
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1 Stars
81 Commits
2 Forks
2 Watching
3 Branches
2 Contributors
Updated on 26 Oct 2024
TypeScript (93.11%)
JavaScript (3.71%)
Shell (3.17%)
Cumulative downloads
Total Downloads
Last day
-77.8%
2
Compared to previous day
Last week
-81.8%
8
Compared to previous week
Last month
-55.2%
124
Compared to previous month
Last year
37.4%
849
Compared to previous year
2
1
Caching mock fetch implementation for all runtimes and frameworks.
Copyright (c) 2023 by Gadi Cohen. MIT Licensed.
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!! ("Test Driven Development").
Not only do you get a muuuch faster feedback loop, but you can commit the cache to your repository / source control so your entire team benefits, and for CI. Based off earlier work in yahoo-finance2 where we test 1400+ API "calls" in < 3s on every commit. Feature requests welcome!
NB: if you're still using v1 (formerly jest-fetch-mock-cache
),
see the old README
and/or MIGRATING.md for how to upgrade.
Generally your code will look something like this, but, see further below for the exact code for different runtimes and testing frameworks.
1import createFetchCache from "fetch-mock-cache"; 2// See list of possible stores, below. 3import Store from "fetch-mock-cache/lib/stores/fs"; 4 5const fetchCache = createFetchCache({ Store }); 6 7describe("cachingMock", () => { 8 it("works with a JSON response", async (t) => { 9 const url = "http://echo.jsontest.com/key/value/one/two"; 10 const expectedResponse = { one: "two", key: "value" }; 11 t.mock.method(globalThis, "fetch", fetchCache); 12 13 for (let i = 0; i < 2; i++) { 14 const response = await fetch(url); 15 const data = await response.json(); 16 const expectedCacheHeader = i === 0 ? "MISS" : "HIT"; 17 expect(response.headers.get("X-FMC-Cache")).toBe(expectedCacheHeader); 18 expect(data).toEqual(expectedResponse); 19 } 20 }); 21});
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.
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 | direct or with fetch-mock | |
jest | direct or with jest-fetch-mock | ||
vitest | direct or with vitest-fetch-mock | ||
Deno | deno test | direct | |
Bun | bun:test | direct, maybe soon bun-bagel |
Sample output from the Quick Start code above, when used with NodeFSStore
:
1$ cat tests/fixtures/http/echo.jsontest.com\!key\!value\!one\!two
1{ 2 "request": { 3 "url": "http://echo.jsontest.com/key/value/one/two" 4 }, 5 "response": { 6 "ok": true, 7 "status": 200, 8 "statusText": "OK", 9 "headers": { 10 "access-control-allow-origin": "*", 11 "connection": "close", 12 "content-length": "39", 13 "content-type": "application/json", 14 "date": "Fri, 21 Jul 2023 16:59:17 GMT", 15 "server": "Google Frontend", 16 "x-cloud-trace-context": "344994371e51195ae21f236e5d7650c4" 17 }, 18 "bodyJson": { 19 "one": "two", 20 "key": "value" 21 } 22 } 23}
For non-JSON bodies, a bodyText
is stored as a string. We store an
object as bodyJson
for readability reasons.
We use debug for debugging. E.g.:
1$ DEBUG=fetch-mock-cache:* yarn test 2yarn run v1.22.19 3$ jest 4 fetch-mock-cache:core Fetching and caching 'http://echo.jsontest.com/key/value/one/two' +0ms 5 fetch-mock-cache:core Using cached copy of 'http://echo.jsontest.com/key/value/one/two' +177ms 6 PASS src/index.spec.ts 7 cachingMock 8 ✓ should work (180 ms)
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.
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:
1import FMCStore from "fetch-mock-cache/store"; 2import type { FMCCacheContent, FMCStoreOptions } from "fetch-mock-cache/store"; 3import db from "./db"; // your existing db 4 5export default class MyStore extends FMCStore { 6 async fetchContent(req: FMCCacheContent["request"]) { 7 const _id = await this.idFromRequest(request); 8 return (await db.collection("fmc").findOne({ _id })).content; 9 } 10 async storeContent(content: FMCCacheContent) { 11 const _id = await this.idFromRequest(content.request); 12 await db.collection("jfmc").insertOne({ _id, content }); 13 } 14}
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:
1// These will be used for the next fetch call ONCE only. However, `_once()` 2// may be called multiple times to queue options for multiple future calls. 3fetchCache._once({ 4 /* options */ 5});
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.
In this case, we can:
1fetchCache._once({ id: "mytest" }); 2fetch(/* ... */); // 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).
No vulnerabilities found.
No security vulnerabilities found.