{"id":15440881,"url":"https://github.com/samuelcolvin/edge-mock","last_synced_at":"2025-04-12T22:37:18.149Z","repository":{"id":43290480,"uuid":"376351966","full_name":"samuelcolvin/edge-mock","owner":"samuelcolvin","description":"Tools for testing and developing CloudFlare worker apps.","archived":false,"fork":false,"pushed_at":"2024-07-21T07:08:43.000Z","size":187,"stargazers_count":54,"open_issues_count":6,"forks_count":5,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-10T23:36:59.309Z","etag":null,"topics":["cloudflare-workers","service-worker","typescript","unit-testing"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/edge-mock","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/samuelcolvin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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":"2021-06-12T17:48:49.000Z","updated_at":"2025-03-08T14:56:47.000Z","dependencies_parsed_at":"2024-06-19T00:01:44.015Z","dependency_job_id":"d5023d46-725f-4a83-8601-916c9156692e","html_url":"https://github.com/samuelcolvin/edge-mock","commit_stats":{"total_commits":68,"total_committers":2,"mean_commits":34.0,"dds":"0.014705882352941124","last_synced_commit":"11e6c03e3649d9c84cf1f1fad7bdabe9f86f9d18"},"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samuelcolvin%2Fedge-mock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samuelcolvin%2Fedge-mock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samuelcolvin%2Fedge-mock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samuelcolvin%2Fedge-mock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/samuelcolvin","download_url":"https://codeload.github.com/samuelcolvin/edge-mock/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248643007,"owners_count":21138353,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["cloudflare-workers","service-worker","typescript","unit-testing"],"created_at":"2024-10-01T19:15:42.328Z","updated_at":"2025-04-12T22:37:18.127Z","avatar_url":"https://github.com/samuelcolvin.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# edge-mock\n\n[![ci](https://github.com/samuelcolvin/edge-mock/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/samuelcolvin/edge-mock/actions?query=branch%3Amain)\n[![codecov](https://codecov.io/gh/samuelcolvin/edge-mock/branch/main/graph/badge.svg)](https://codecov.io/gh/samuelcolvin/edge-mock)\n\nTools for developing and testing edge service workers, in particular CloudFlare workers.\n\n_edge-mock_ provides three things:\n1. Implementations for types used in service-workers, e.g. `Request`, `Respones`, `FetchEvent` `ReadableStream` etc.\n2. A function `makeEdgeEnv` for installing these types into the global namespace for use in unit tests\n3. A simple HTTP server based on `express.js` which lets you run your service-worker based app locally for development\n\nYou can consider _edge-mock_ as implementing the most commonly used types declare in the\n[`@cloudflare/workers-types`](https://www.npmjs.com/package/@cloudflare/workers-types) typescript types package.\n\nWhile _edge-mock_ is designed to be useful when developing \n[CloudFlare worker](https://developers.cloudflare.com/workers/) applications, it should be usable while developing\nany service-worker app including for (future) alternative edge worker implementations.\n\n_edge-mock_ is written in TypeScript and while you may be able to use it from vanilla javascript projects, you'd be\nbetter off writing your code in TypeScript!\n\n## Install\n\n    [npm/yarn] add edge-mock\n\n## Usage\n\n_edge-mock_ provides the following types (all available to import from `edge-mock`):\n\n* `EdgeRequest` - implements the [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) interface\n  of the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), with the addition of the\n  [`cf`](https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties) attribute\n  provided in CloudFlare workers.\n* `EdgeResponse` - implements the [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) interface\n* `EdgeFetchEvent` - implements the [`FetchEvent`](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent) interface,\n  with many attributes set to `undefined` to match `FetchEvent`s in CloudFlare workers\n* `EdgeBlob` - implements the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) interface\n* `EdgeFormData` implements the [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) interface\n* `EdgeFile` implements the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) \n  interface as used by `FormData`\n* `EdgeHeaders` - implements the [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) interface\n* `EdgeReadableStream` - in memory implementation of the \n  [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) interface\n* `EdgeKVNamespace` - in memory implementation of CloudFlare's \n  [KVNamespace](https://developers.cloudflare.com/workers/runtime-apis/kv)\n* `stub_fetch` - a very simple mock for \n  [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) which returns `200`\n  for requests to `https://example.com/` and `404` for all other requests\n* `makeEdgeEnv` - which installs all the above types (except `EdgeKVNamespace`) into `global` so they can be\n  used in worker scripts; types are installed into global by the name of the type they shadow, e.g. `EdgeRequest`\n  is assigned to `global` as `Request`\n\nThere's also `fetch_live` (import with `import live_fetch from 'edge-mock/live_fetch'`) which is an implementation\nof `fetch` which makes actual http requests using `node-fetch`. It is installed by default instead of\n`stub_fetch` in the dev server, see below.\n\n**Please Note**: all the above types are designed for use with node while testing and are vanilla in-memory\nonly implementations. They are not designed for production use or with large payloads.\n\n### Example of Usage for unit testing\n\n_edge-mock_ works well with [jest](https://jestjs.io/) to make writing unit tests for edge workers delightful.\n\nLet's say you have the following `handler.ts` with a function `handleRequest` that you want to test:\n\n```ts\nexport async function handleRequest(event: FetchEvent): Promise\u003cResponse\u003e {\n  const {request} = event\n  const method = request.method\n  let body: string | null = null\n  if (method == 'POST') {\n    body = await request.text()\n  }\n  const url = new URL(request.url)\n  const response_info = {\n    method,\n    headers: Object.fromEntries(request.headers.entries()),\n    searchParams: Object.fromEntries(url.searchParams.entries()),\n    body,\n  }\n  const headers = {'content-type': 'application/json'}\n  return new Response(JSON.stringify(response_info, null, 2), {headers})\n}\n```\n\n(To see how this would be deployed to cloudflare, see the \n[cloudflare worker TypeScript template](https://github.com/cloudflare/worker-typescript-template))\n\nTo test the above `handleRequest` function, you could use the following:\n\n```ts\nimport {makeEdgeEnv} from 'edge-mock'\nimport {handleRequest} from '../src/handle.ts'\n\ndescribe('handleRequest', () =\u003e {\n  beforeEach(() =\u003e {\n    makeEdgeEnv()\n    jest.resetModules()\n  })\n\n  test('post', async () =\u003e {\n    // Request is available here AND in handleRequest because makeEdgeEnv installed\n    // the proxy EdgeRequest into global under that name\n    const request = new Request('/?foo=1', {method: 'POST', body: 'hello'})\n    // same with FetchEvent, Response etc.\n    const event = new FetchEvent('fetch', {request})\n    const response = await handleRequest(event)\n    expect(response.status).toEqual(200)\n    expect(await response.json()).toStrictEqual({\n      method: 'POST',\n      headers: {accept: '*/*'},\n      searchParams: {foo: '1'},\n      body: 'hello',\n    })\n  })\n})\n```\n\n### Development Server\n\nThe development server relies on webpack and uses webpack-watch to reload the server on code changes.\n\nTo run the server, add the following to the `scripts` section of `package.json`:\n\n```json\n  ...\n  \"scripts\": {\n    \"dev\": \"edge-mock-server\",\n    ...\n  },\n  ...\n```\n\n**TODO:** explain how `edge-mock-config.js` works.\n\nYou can then run the dev server with:\n\n```bash\nyarn dev\n```\n\n(or `npm run dev` if you use `npm` rather than `yarn`)\n\n# Documentation\n\n## KV store\n\n```ts\nimport {EdgeKVNamespace as KVNamespace} from 'edge-mock';\ndescribe('edge-mock', () =\u003e {\n    test('put and get kv', async() =\u003e {\n        const kv = new KVNamespace();\n        await kv.put('foo','bar');\n        const value = await kv.get('foo');\n        expect(value).toBe('bar');\n    });\n});\n```\n\n### Wrangler sites integration\n\nTODO\n\n## Request Payload\n\nTODO\n\n### JSON\n\nTODO\n\n### FormData\n\nTODO\n\n### Binary Data, ArrayBuffer\n\nTODO\n\n## Request.cf\n\nTODO\n\n## fetch mocking\n\nTODO\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamuelcolvin%2Fedge-mock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsamuelcolvin%2Fedge-mock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamuelcolvin%2Fedge-mock/lists"}