|
| 1 | +# `@msw/cloudflare` |
| 2 | + |
| 3 | +Develop and test Cloudflare applications with Mock Service Worker. |
| 4 | + |
| 5 | +## Getting started |
| 6 | + |
| 7 | +### Install |
| 8 | + |
| 9 | +```sh |
| 10 | +npm i pkg.pr.new/mswjs/cloudflare/@msw/cloudflare@beta msw |
| 11 | +``` |
| 12 | + |
| 13 | +> This package requires `msw` as a peer dependency. |
| 14 | +
|
| 15 | +### Usage |
| 16 | + |
| 17 | +Let's say your worker performs a GET request to `https://example.com/user`. |
| 18 | + |
| 19 | +```ts |
| 20 | +// worker.ts |
| 21 | +export default { |
| 22 | + async fetch(req, env, ctx) { |
| 23 | + const response = await fetch('https://api.example.com/user') |
| 24 | + const user = await response.json() |
| 25 | + |
| 26 | + return new Response(user.id, { |
| 27 | + headers: { 'content-type': 'text/plain' }, |
| 28 | + }) |
| 29 | + }, |
| 30 | +} |
| 31 | +``` |
| 32 | + |
| 33 | +Here's how you can intercept and mock that third-party request in order to reliably test your worker in Vitest. |
| 34 | + |
| 35 | +```ts |
| 36 | +import { env } from 'cloudflare:workers' |
| 37 | +import { createExecutionContext } from 'cloudflare:test' |
| 38 | +import { http, HttpResponse } from 'msw' |
| 39 | +import { setupNetwork } from '@msw/cloudflare' |
| 40 | +import worker from './worker' |
| 41 | + |
| 42 | +const network = setupNetwork() |
| 43 | + |
| 44 | +beforeAll(() => { |
| 45 | + network.enable() |
| 46 | +}) |
| 47 | + |
| 48 | +afterEach(() => { |
| 49 | + network.resetHandlers() |
| 50 | +}) |
| 51 | + |
| 52 | +afterAll(() => { |
| 53 | + network.disable() |
| 54 | +}) |
| 55 | + |
| 56 | +it('', async () => { |
| 57 | + network.use( |
| 58 | + http.get('https://api.example.com/user', () => { |
| 59 | + return HttpResponse.json({ id: 1, name: 'John Maverick' }) |
| 60 | + }), |
| 61 | + ) |
| 62 | + |
| 63 | + const ctx = createExecutionContext() |
| 64 | + const response = await worker.fetch( |
| 65 | + new Request('http://localhost/'), |
| 66 | + env, |
| 67 | + ctx, |
| 68 | + ) |
| 69 | + |
| 70 | + expect.soft(response.status).toBe(200) |
| 71 | + await expect.soft(response.text()).resolves.toBe('1') |
| 72 | +}) |
| 73 | +``` |
| 74 | + |
| 75 | +## Related materials |
| 76 | + |
| 77 | +- [**Write your first test in Cloudflare Docs**](https://developers.cloudflare.com/workers/testing/vitest-integration/write-your-first-test/) |
| 78 | +- [Mocking HTTP with MSW](https://mswjs.io/docs/http/) |
| 79 | +- [Mocking GraphQL with MSW](https://mswjs.io/docs/graphql/) |
| 80 | +- [Mocking WebSocket with MSW](https://mswjs.io/docs/websocket/) |
0 commit comments