|
1 | 1 | # `@aryzing/bun-mock-fetch`
|
| 2 | + |
| 3 | +Mock fetch requests in Bun. Particularly useful when running tests. |
| 4 | + |
| 5 | +```shell |
| 6 | +bun add @aryzing/bun-mock-fetch |
| 7 | +``` |
| 8 | + |
| 9 | +Example usage: |
| 10 | + |
| 11 | +```typescript |
| 12 | +// Returns 200 OK by default |
| 13 | +mockFetch("https://example.com"); |
| 14 | + |
| 15 | +// Using minimatch |
| 16 | +mockFetch("https://example.com/foo/**"); |
| 17 | + |
| 18 | +// Using regex |
| 19 | +mockFetch(/.*example.*/); |
| 20 | + |
| 21 | +mockFetch("https://example.com/foo/**", { |
| 22 | + // Must have these headers. |
| 23 | + headers: { "x-example-header": "example-value" }, |
| 24 | + // Must use this method. |
| 25 | + method: "GET", |
| 26 | + response: { |
| 27 | + data: JSON.stringify({ foo: "bar" }), |
| 28 | + headers: { "Content-Type": "application/json" }, |
| 29 | + status: 200, |
| 30 | + }, |
| 31 | +}); |
| 32 | +``` |
| 33 | + |
| 34 | +Example in tests, |
| 35 | + |
| 36 | +```typescript |
| 37 | +afterEach(() => { |
| 38 | + clearFetchMocks(); |
| 39 | +}); |
| 40 | + |
| 41 | +test("first test", async () => { |
| 42 | + mockFetch("https://api.example.com", { |
| 43 | + response: { |
| 44 | + data: "first", |
| 45 | + }, |
| 46 | + }); |
| 47 | + expect(await makeApiRequest()).toBe("first"); |
| 48 | +}); |
| 49 | + |
| 50 | +test("second test", async () => { |
| 51 | + mockFetch("https://api.example.com", { |
| 52 | + response: { |
| 53 | + data: "second", |
| 54 | + }, |
| 55 | + }); |
| 56 | + expect(await makeApiRequest()).toBe("second"); |
| 57 | +}); |
| 58 | +``` |
| 59 | + |
| 60 | +The `mockFetch` method may be called several times to define multiple mocks. Requests will at be matched at most against one mock, with later mocks take precendece over earlier mocks. |
| 61 | + |
| 62 | +By default, requests that aren't matched against any mock definitions are forwarded to the native built-in fetch. This behavior can be modified using `setIsUsingBuiltInFetchFallback()`. |
| 63 | + |
| 64 | +To clear the mocks and restore original built-in fetch, |
| 65 | + |
| 66 | +```typescript |
| 67 | +clearFetchMocks(); |
| 68 | +``` |
| 69 | + |
| 70 | +## Helpers |
| 71 | + |
| 72 | +- `setIsUsingBuiltInFetchFallback(value: boolean)`: Enable or disable using the built-in fetch for requests that haven't been matched against any mocks. Enabled by default. |
| 73 | +- `setIsVerbose(value: boolean)`: Enable or disable debugging logs. Disabled by default. |
0 commit comments