0
# Jest Fetch Mock
1
2
Jest Fetch Mock provides a comprehensive mocking solution for the fetch API in Jest testing environments. It enables developers to easily mock HTTP requests made with fetch() by providing configurable mock responses, supporting both successful and failed request scenarios, and offering utilities for inspecting mock call history.
3
4
## Package Information
5
6
- **Package Name**: jest-fetch-mock
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install --save-dev jest-fetch-mock`
10
11
## Core Imports
12
13
```javascript
14
const fetchMock = require("jest-fetch-mock");
15
```
16
17
For ES6/TypeScript:
18
19
```typescript
20
import fetchMock from "jest-fetch-mock";
21
// or
22
import { enableFetchMocks, disableFetchMocks } from "jest-fetch-mock";
23
```
24
25
## Basic Usage
26
27
```javascript
28
// Enable mocking in setup file
29
require("jest-fetch-mock").enableMocks();
30
31
// In your test
32
beforeEach(() => {
33
fetch.resetMocks();
34
});
35
36
it("should fetch users", async () => {
37
fetch.mockResponseOnce(JSON.stringify({ users: ["Alice", "Bob"] }));
38
39
const response = await fetch("/users");
40
const data = await response.json();
41
42
expect(data.users).toEqual(["Alice", "Bob"]);
43
expect(fetch.mock.calls.length).toEqual(1);
44
expect(fetch.mock.calls[0][0]).toEqual("/users");
45
});
46
```
47
48
## Architecture
49
50
Jest Fetch Mock is built around several key components:
51
52
- **Fetch Mock Function**: Drop-in replacement for native fetch with Jest mock capabilities
53
- **Response Mocking**: Flexible system for mocking successful HTTP responses
54
- **Error/Rejection Mocking**: Support for mocking network failures and HTTP errors
55
- **Conditional Mocking**: URL-based and predicate-based selective mocking
56
- **Global Setup**: Integration with Jest's global mocking system
57
- **TypeScript Support**: Complete type definitions for all functionality
58
59
## Capabilities
60
61
### Response Mocking
62
63
Core functionality for mocking successful HTTP responses with configurable bodies and options. Supports both one-time and persistent mocks.
64
65
```javascript { .api }
66
// Mock single response for all calls
67
fetch.mockResponse(bodyOrFunction, init);
68
69
// Mock single response for next call only
70
fetch.mockResponseOnce(bodyOrFunction, init);
71
72
// Alias for mockResponseOnce
73
fetch.once(bodyOrFunction, init);
74
75
// Mock multiple responses in sequence
76
fetch.mockResponses(...responses);
77
```
78
79
[Response Mocking](./response-mocking.md)
80
81
### Error and Abort Handling
82
83
Functionality for mocking network failures, HTTP errors, and request aborts. Essential for testing error handling in your application.
84
85
```javascript { .api }
86
// Mock rejection with error
87
fetch.mockReject(errorOrFunction);
88
fetch.mockRejectOnce(errorOrFunction);
89
90
// Mock request abort
91
fetch.mockAbort();
92
fetch.mockAbortOnce();
93
```
94
95
[Error and Abort Handling](./error-abort-handling.md)
96
97
### Conditional Mocking
98
99
Advanced mocking capabilities that allow selective mocking based on URL patterns or custom predicates. Enables fine-grained control over which requests are mocked.
100
101
```javascript { .api }
102
// Check if request should be mocked
103
fetch.isMocking(input, reqInit);
104
105
// Conditional mocking based on URL/predicate
106
fetch.mockIf(urlOrPredicate, bodyOrFunction, init);
107
fetch.dontMockIf(urlOrPredicate, bodyOrFunction, init);
108
109
// Enable/disable mocking globally
110
fetch.doMock(bodyOrFunction, init);
111
fetch.dontMock();
112
```
113
114
[Conditional Mocking](./conditional-mocking.md)
115
116
### Mock Management
117
118
Utilities for managing mock state, resetting mocks between tests, and controlling global mocking behavior.
119
120
```javascript { .api }
121
// Reset mock state
122
fetch.resetMocks();
123
124
// Global mock control
125
fetch.enableMocks();
126
fetch.disableMocks();
127
```
128
129
[Mock Management](./mock-management.md)
130
131
## Types
132
133
```typescript { .api }
134
interface FetchMock extends jest.MockInstance<Promise<Response>, [string | Request | undefined, RequestInit | undefined]> {
135
(input?: string | Request, init?: RequestInit): Promise<Response>;
136
// All methods documented in capability sections above
137
}
138
139
interface MockParams {
140
status?: number;
141
statusText?: string;
142
headers?: string[][] | { [key: string]: string };
143
url?: string;
144
}
145
146
interface MockResponseInit extends MockParams {
147
body?: string;
148
init?: MockParams;
149
}
150
151
type ErrorOrFunction = Error | ((...args: any[]) => Promise<any>);
152
type UrlOrPredicate = string | RegExp | ((input: Request) => boolean);
153
type MockResponseInitFunction = (request: Request) => Promise<MockResponseInit | string>;
154
```
155
156
## Properties
157
158
```javascript { .api }
159
// Web API constructors available on fetch object
160
fetch.Headers; // Native Headers constructor
161
fetch.Response; // Custom Response wrapper with mock support
162
fetch.Request; // Native Request constructor
163
```