-
Notifications
You must be signed in to change notification settings - Fork 188
/
Copy pathmocked-storage.js
109 lines (89 loc) · 2.63 KB
/
mocked-storage.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/* eslint-disable no-var */
/* eslint-disable prefer-reflect */
/* eslint-disable modules/no-cjs */
var mixIn = require('mout/object/mixIn');
/* global window:true */
/**
* Create window as event target
*/
var window = mixIn({}, sinon.EventTarget);
/* global StorageEvent:true */
/**
* Custom event
* @constructor
*/
function StorageEvent(type, customData, target) {
this.initEvent(type, false, false, target);
mixIn(this, customData);
}
StorageEvent.prototype = new sinon.Event();
StorageEvent.prototype.constructor = StorageEvent;
/**
* Mocked storage (initially borrowed from https://github.com/azu/mock-localstorage)
* @constructor
*/
function MockedStorage() {
var storage = {};
var defaultProps = {
writable: false,
configurable: false,
enumerable: false
};
function dispatchEvent(key, value) {
var storageEvent = new StorageEvent('storage', {
key: key,
oldValue: storage[key],
newValue: value,
url: '/'
});
setTimeout(function () {
window.dispatchEvent(storageEvent);
}, 0);
}
Object.defineProperty(storage, 'getItem', mixIn({
value: function (key) {
if (arguments.length === 0) {
throw new TypeError('Failed to execute \'getItem\' on \'Storage\': 1 argument required, but only 0 present.');
}
return storage[key.toString()] || null;
}
}, defaultProps));
Object.defineProperty(storage, 'setItem', mixIn({
value: function (key, value) {
if (arguments.length < 2) {
throw new TypeError('Failed to execute \'setItem\' on \'Storage\': 1 argument required, but only ' + arguments.length + ' present.');
}
var stringKey = String(key);
var stringValue = String(value);
dispatchEvent(stringKey, stringValue);
storage[stringKey] = stringValue;
}
}, defaultProps));
Object.defineProperty(storage, 'removeItem', mixIn({
value: function (key) {
if (arguments.length === 0) {
throw new TypeError('Failed to execute \'removeItem\' on \'Storage\': 1 argument required, but only 0 present.');
}
var stringKey = String(key);
dispatchEvent(stringKey, null);
delete storage[stringKey];
}
}, defaultProps));
Object.defineProperty(storage, 'length', {
get: function () {
return Object.keys(storage).length;
},
configurable: false,
enumerable: false
});
Object.defineProperty(storage, 'clear', mixIn({
value: function () {
Object.keys(storage).forEach(function (key) {
storage.removeItem(key);
});
}
}, defaultProps));
return storage;
}
window.localStorage = new MockedStorage();
module.exports = window;