Skip to content

Commit e2e97db

Browse files
committed
Update docs
1 parent cc0533b commit e2e97db

File tree

2 files changed

+73
-1
lines changed

2 files changed

+73
-1
lines changed

README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,73 @@
11
# `@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.

src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ export type MockOptions = {
1515
export interface MockResponse {
1616
data?: any;
1717
status?: number;
18-
headers?: Headers;
18+
headers?: Record<string, string>;
1919
}

0 commit comments

Comments
 (0)