Auto mock all localStorage and sessionStorage APIs for your Jest tests
npx @tessl/cli install tessl/npm-jest-localstorage-mock@2.4.00
# Jest LocalStorage Mock
1
2
Jest LocalStorage Mock provides working localStorage and sessionStorage APIs for Jest tests. It auto-mocks both storage APIs with Jest spy functions, enabling comprehensive testing of web applications that rely on browser storage without requiring a browser environment.
3
4
## Package Information
5
6
- **Package Name**: jest-localstorage-mock
7
- **Package Type**: npm
8
- **Language**: JavaScript (ES6 modules)
9
- **Installation**: `npm install --save-dev jest-localstorage-mock` or `yarn add --dev jest-localstorage-mock`
10
11
## Core Imports
12
13
Setup typically happens via Jest configuration (no explicit imports needed):
14
15
```json
16
{
17
"jest": {
18
"resetMocks": false,
19
"setupFiles": ["jest-localstorage-mock"]
20
}
21
}
22
```
23
24
Manual setup:
25
26
```javascript
27
import "jest-localstorage-mock";
28
// or
29
require("jest-localstorage-mock");
30
```
31
32
For create-react-app projects, add to `src/setupTests.js`:
33
34
```javascript
35
require('jest-localstorage-mock');
36
```
37
38
And override Jest config in `package.json`:
39
40
```json
41
{
42
"jest": {
43
"resetMocks": false
44
}
45
}
46
```
47
48
For direct LocalStorage class usage:
49
50
```javascript
51
import { LocalStorage } from "jest-localstorage-mock/src/localstorage";
52
```
53
54
## Basic Usage
55
56
```javascript
57
// After setup, localStorage and sessionStorage are available globally
58
test('should save to localStorage', () => {
59
const KEY = 'foo', VALUE = 'bar';
60
61
// Use localStorage/sessionStorage normally
62
localStorage.setItem(KEY, VALUE);
63
64
// Test with Jest spies
65
expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
66
expect(localStorage.__STORE__[KEY]).toBe(VALUE);
67
expect(Object.keys(localStorage.__STORE__).length).toBe(1);
68
});
69
70
// Clear storage between tests
71
beforeEach(() => {
72
localStorage.clear();
73
jest.clearAllMocks();
74
});
75
```
76
77
## Capabilities
78
79
### LocalStorage Class
80
81
Core mock implementation that provides all localStorage/sessionStorage methods as Jest spy functions.
82
83
```javascript { .api }
84
/**
85
* LocalStorage mock class with Jest spy functions
86
* @param {Object} jest - Jest instance for creating mock functions
87
*/
88
class LocalStorage {
89
constructor(jest);
90
91
/** Get item from storage (Jest spy) */
92
getItem(key: string): string | null;
93
94
/** Store item in storage (Jest spy) - values coerced to string */
95
setItem(key: string, val: any): void;
96
97
/** Remove item from storage (Jest spy) */
98
removeItem(key: string): void;
99
100
/** Clear all items from storage (Jest spy) */
101
clear(): void;
102
103
/** Get key at specified index (Jest spy) */
104
key(idx: number): string | null;
105
106
/** Return string representation '[object Storage]' (Jest spy) */
107
toString(): string;
108
109
/** Number of items in storage */
110
get length(): number;
111
112
/** Direct access to storage object for test assertions */
113
get __STORE__(): LocalStorage;
114
}
115
```
116
117
### Storage API Methods
118
119
All standard Web Storage API methods are provided as Jest spy functions.
120
121
```javascript { .api }
122
/**
123
* Get item from storage
124
* @param {string} key - Storage key
125
* @returns {string|null} Stored value or null if not found
126
*/
127
getItem(key: string): string | null;
128
129
/**
130
* Store item in storage
131
* @param {string} key - Storage key
132
* @param {any} val - Value to store (coerced to string)
133
*/
134
setItem(key: string, val: any): void;
135
136
/**
137
* Remove item from storage
138
* @param {string} key - Storage key to remove
139
*/
140
removeItem(key: string): void;
141
142
/**
143
* Clear all items from storage
144
*/
145
clear(): void;
146
147
/**
148
* Get key name at specified index
149
* @param {number} idx - Index of key to retrieve
150
* @returns {string|null} Key name or null if index out of bounds
151
*/
152
key(idx: number): string | null;
153
```
154
155
### Storage Properties
156
157
```javascript { .api }
158
/**
159
* Number of items currently stored
160
*/
161
length: number;
162
163
/**
164
* Direct access to storage object for test assertions
165
* Backwards compatibility property
166
*/
167
__STORE__: LocalStorage;
168
```
169
170
### Global Setup
171
172
The setup file automatically creates mock instances on the global scope.
173
174
```javascript { .api }
175
/**
176
* Global localStorage mock (automatically created)
177
*/
178
global.localStorage: LocalStorage;
179
180
/**
181
* Global sessionStorage mock (automatically created)
182
*/
183
global.sessionStorage: LocalStorage;
184
185
/**
186
* Alternative localStorage mock (non-writable, if _localStorage exists)
187
*/
188
global._localStorage?: LocalStorage;
189
190
/**
191
* Alternative sessionStorage mock (non-writable, if _sessionStorage exists)
192
*/
193
global._sessionStorage?: LocalStorage;
194
```
195
196
## Usage Examples
197
198
### Basic Storage Operations
199
200
```javascript
201
test('localStorage operations', () => {
202
// Store data
203
localStorage.setItem('user', 'alice');
204
localStorage.setItem('theme', 'dark');
205
206
// Retrieve data
207
expect(localStorage.getItem('user')).toBe('alice');
208
expect(localStorage.getItem('missing')).toBeNull();
209
210
// Check storage state
211
expect(localStorage.length).toBe(2);
212
expect(localStorage.key(0)).toBe('user');
213
214
// Remove data
215
localStorage.removeItem('theme');
216
expect(localStorage.length).toBe(1);
217
218
// Clear all
219
localStorage.clear();
220
expect(localStorage.length).toBe(0);
221
});
222
```
223
224
### Jest Spy Assertions
225
226
```javascript
227
test('storage method calls', () => {
228
localStorage.setItem('key', 'value');
229
230
// Verify method was called
231
expect(localStorage.setItem).toHaveBeenCalledTimes(1);
232
expect(localStorage.setItem).toHaveBeenLastCalledWith('key', 'value');
233
234
// Verify method was not called
235
expect(localStorage.removeItem).not.toHaveBeenCalled();
236
});
237
```
238
239
### Direct Storage Access
240
241
```javascript
242
test('direct storage inspection', () => {
243
localStorage.setItem('item1', 'value1');
244
localStorage.setItem('item2', 'value2');
245
246
// Access storage object directly
247
expect(localStorage.__STORE__.item1).toBe('value1');
248
expect(localStorage.__STORE__.item2).toBe('value2');
249
250
// Check all stored keys
251
const keys = Object.keys(localStorage.__STORE__);
252
expect(keys).toEqual(['item1', 'item2']);
253
});
254
```
255
256
### Type Coercion Behavior
257
258
```javascript
259
test('value coercion to string', () => {
260
// All values are coerced to strings
261
localStorage.setItem('number', 42);
262
localStorage.setItem('boolean', true);
263
localStorage.setItem('object', { key: 'value' });
264
265
expect(localStorage.getItem('number')).toBe('42');
266
expect(localStorage.getItem('boolean')).toBe('true');
267
expect(localStorage.getItem('object')).toBe('[object Object]');
268
});
269
```
270
271
### Storage Object Behavior
272
273
```javascript
274
test('storage object behavior', () => {
275
// toString returns proper representation
276
expect(localStorage.toString()).toBe('[object Storage]');
277
expect(localStorage.toString).toHaveBeenCalled();
278
279
// Verify key method behavior
280
localStorage.setItem('first', 'value1');
281
localStorage.setItem('second', 'value2');
282
283
expect(localStorage.key(0)).toMatch(/^(first|second)$/);
284
expect(localStorage.key(999)).toBeNull();
285
});
286
```
287
288
### Test Cleanup
289
290
```javascript
291
describe('localStorage tests', () => {
292
beforeEach(() => {
293
// Clear storage data
294
localStorage.clear();
295
296
// Reset Jest mocks
297
jest.clearAllMocks();
298
// Or reset individual mocks:
299
// localStorage.setItem.mockClear();
300
});
301
302
test('clean state for each test', () => {
303
expect(localStorage.length).toBe(0);
304
expect(localStorage.setItem).toHaveBeenCalledTimes(0);
305
});
306
});
307
```