0
# Testing Utilities
1
2
Jest Expo provides powerful testing utilities for mocking object properties and React Native APIs during tests. These utilities help create controlled testing environments and mock external dependencies effectively.
3
4
## Capabilities
5
6
### Property Mocking
7
8
Utilities for temporarily replacing object properties during tests with automatic restoration capabilities.
9
10
#### Mock Property
11
12
```javascript { .api }
13
/**
14
* Mock a property on an object during testing
15
* @param object - Target object to mock property on
16
* @param property - Property name to mock
17
* @param mockValue - Value to replace the property with
18
*/
19
function mockProperty<T>(object: T, property: keyof T, mockValue: any): void;
20
```
21
22
**Features:**
23
- Saves original property descriptor for restoration
24
- Handles configurable, enumerable, and writable attributes
25
- Supports any object type and property value
26
- Maintains property metadata for proper restoration
27
28
**Usage Example:**
29
30
```javascript
31
import { mockProperty, unmockProperty } from "jest-expo";
32
33
describe("Console mocking", () => {
34
beforeEach(() => {
35
// Mock console.warn to capture warnings
36
mockProperty(console, "warn", jest.fn());
37
});
38
39
afterEach(() => {
40
// Restore original console.warn
41
unmockProperty(console, "warn");
42
});
43
44
test("should not show warnings", () => {
45
console.warn("This warning is mocked");
46
expect(console.warn).toHaveBeenCalledWith("This warning is mocked");
47
});
48
});
49
```
50
51
#### Unmock Property
52
53
```javascript { .api }
54
/**
55
* Restore original property on an object
56
* @param object - Target object to restore property on
57
* @param property - Property name to restore
58
*/
59
function unmockProperty<T>(object: T, property: keyof T): void;
60
```
61
62
**Features:**
63
- Restores original property descriptor exactly
64
- Handles properties that didn't exist originally (removes them)
65
- Cleans up internal references automatically
66
- Safe to call multiple times
67
68
**Usage Example:**
69
70
```javascript
71
import { mockProperty, unmockProperty } from "jest-expo";
72
73
test("property restoration", () => {
74
const originalLog = console.log;
75
76
mockProperty(console, "log", jest.fn());
77
expect(console.log).not.toBe(originalLog);
78
79
unmockProperty(console, "log");
80
expect(console.log).toBe(originalLog);
81
});
82
```
83
84
#### Unmock All Properties
85
86
```javascript { .api }
87
/**
88
* Restore all mocked properties globally across all objects
89
*/
90
function unmockAllProperties(): void;
91
```
92
93
**Features:**
94
- Restores all properties mocked with `mockProperty`
95
- Works across all objects and test suites
96
- Useful for test cleanup and preventing test interference
97
- Clears all internal tracking references
98
99
**Usage Example:**
100
101
```javascript
102
import { mockProperty, unmockAllProperties } from "jest-expo";
103
104
describe("Test suite with cleanup", () => {
105
afterAll(() => {
106
// Restore all mocked properties at once
107
unmockAllProperties();
108
});
109
110
test("multiple mocks", () => {
111
mockProperty(console, "log", jest.fn());
112
mockProperty(console, "warn", jest.fn());
113
mockProperty(global, "fetch", jest.fn());
114
115
// Test code here...
116
});
117
});
118
```
119
120
### React Native API Mocking
121
122
Specialized utilities for mocking React Native APIs, particularly the Linking API for navigation testing.
123
124
#### Mock Linking
125
126
```javascript { .api }
127
/**
128
* Mock React Native Linking API for testing deep links and navigation
129
* @returns Event dispatcher function for triggering link events
130
*/
131
function mockLinking(): (eventName: string, eventData: any) => void;
132
```
133
134
**Features:**
135
- Mocks `Linking.addEventListener` and `Linking.removeEventListener`
136
- Provides event dispatcher for simulating link events
137
- Manages listener registration and cleanup
138
- Returns subscription objects with `remove()` method
139
140
**Usage Example:**
141
142
```javascript
143
import { mockLinking, unmockProperty } from "jest-expo";
144
import { Linking } from "react-native";
145
146
describe("Deep link handling", () => {
147
let dispatchLinkEvent;
148
149
beforeEach(() => {
150
dispatchLinkEvent = mockLinking();
151
});
152
153
afterEach(() => {
154
unmockProperty(Linking, "addEventListener");
155
unmockProperty(Linking, "removeEventListener");
156
});
157
158
test("should handle deep links", () => {
159
const linkHandler = jest.fn();
160
161
// Add event listener
162
const subscription = Linking.addEventListener("url", linkHandler);
163
164
// Simulate receiving a deep link
165
dispatchLinkEvent("url", { url: "myapp://profile/123" });
166
167
expect(linkHandler).toHaveBeenCalledWith({ url: "myapp://profile/123" });
168
169
// Clean up
170
subscription.remove();
171
});
172
173
test("should handle listener removal", () => {
174
const linkHandler = jest.fn();
175
176
Linking.addEventListener("url", linkHandler);
177
Linking.removeEventListener("url", linkHandler);
178
179
// This should not trigger the handler
180
dispatchLinkEvent("url", { url: "myapp://test" });
181
182
expect(linkHandler).not.toHaveBeenCalled();
183
});
184
});
185
```
186
187
### Advanced Usage Patterns
188
189
#### Conditional Mocking
190
191
```javascript
192
import { mockProperty, unmockProperty } from "jest-expo";
193
194
describe("Conditional API mocking", () => {
195
test("should mock different APIs based on platform", () => {
196
if (Platform.OS === "ios") {
197
mockProperty(StatusBar, "setBarStyle", jest.fn());
198
} else {
199
mockProperty(StatusBar, "setBackgroundColor", jest.fn());
200
}
201
202
// Platform-specific test logic
203
});
204
});
205
```
206
207
#### Nested Property Mocking
208
209
```javascript
210
import { mockProperty } from "jest-expo";
211
212
test("nested object mocking", () => {
213
const mockConfig = {
214
apiUrl: "https://test-api.example.com",
215
timeout: 5000
216
};
217
218
mockProperty(global, "AppConfig", mockConfig);
219
220
// Test code that uses global.AppConfig
221
});
222
```
223
224
#### Mock Chaining
225
226
```javascript
227
import { mockProperty } from "jest-expo";
228
229
describe("Mock chaining pattern", () => {
230
beforeEach(() => {
231
// Chain multiple mocks for comprehensive API replacement
232
mockProperty(fetch, "prototype", {
233
json: jest.fn().mockResolvedValue({ data: "test" }),
234
text: jest.fn().mockResolvedValue("test response"),
235
ok: true,
236
status: 200
237
});
238
});
239
});
240
```
241
242
## Types
243
244
```typescript { .api }
245
// Utility function signatures
246
declare function mockProperty<T = any>(
247
object: T,
248
property: keyof T,
249
mockValue: any
250
): void;
251
252
declare function unmockProperty<T = any>(
253
object: T,
254
property: keyof T
255
): void;
256
257
declare function unmockAllProperties(): void;
258
259
declare function mockLinking(): (eventName: string, eventData: any) => void;
260
261
// Event dispatcher type
262
type LinkEventDispatcher = (eventName: string, eventData: any) => void;
263
264
// Linking event types
265
interface LinkingEventData {
266
url: string;
267
}
268
269
interface LinkingSubscription {
270
remove(): void;
271
}
272
```