-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstorage.ts
More file actions
48 lines (41 loc) · 1.01 KB
/
storage.ts
File metadata and controls
48 lines (41 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Creates an in-memory Storage mock.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Storage
*/
export class MockStorage implements Storage {
store: {
[key: string]: string;
} = {};
getItem = jest.fn().mockImplementation((k) => this.store[k]);
setItem = jest.fn().mockImplementation((key, value) => {
this.store[key] = `${value}`;
});
removeItem = jest.fn().mockImplementation((key) => {
delete this.store[key];
});
clear = jest.fn().mockImplementation(() => {
this.store = {};
});
get length() {
return Object.keys(this.store).length;
}
key(n: number) {
return Object.keys(this.store)[n];
}
}
export function createStorageMock() {
let mock = new MockStorage();
/**
* Ensure `Object.keys` calls behave similiar to real `Storage`.
*/
mock = new Proxy(mock, {
ownKeys(target) {
return Reflect.ownKeys(target.store);
},
getOwnPropertyDescriptor: () => ({
enumerable: true,
configurable: true,
}),
});
return mock;
}