-
Notifications
You must be signed in to change notification settings - Fork 35
/
store.js
67 lines (55 loc) · 1.5 KB
/
store.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
import { Store } from 'vuex';
Store.prototype.mockGetter = function (name, stub) {
if (!name) {
throw new Error('Getter name must be specified');
}
if (!stub) {
throw new Error('Missing stub function');
}
if (typeof stub !== 'function') {
throw new Error('Stub must be a function');
}
let store = this;
let mockedGetters = store.__mockedGetters = store.__mockedGetters || new Map();
if (mockedGetters.has(name)) {
throw new Error(`Cannot mock getter with the name '${name}' twice. Restore the getter or call stub.reset() instead.`);
}
mockedGetters.set(name, stub);
let gettersProxy = store.__gettersProxy;
if (!gettersProxy) {
store.__gettersProxy = gettersProxy = new Proxy(store.getters, {
get (getters, propName) {
if (mockedGetters.has(propName)) {
return mockedGetters.get(propName).call(store);
} else {
return getters[propName];
}
}
});
store.__originalGetters = store.getters;
Object.defineProperty(store, 'getters', {
get () {
return gettersProxy;
}
});
}
return {
restore () {
mockedGetters.delete(name);
}
};
};
Store.prototype.restore = function () {
let store = this;
if (store.__originalGetters) {
let getters = store.__originalGetters;
Object.defineProperty(store, 'getters', {
get () {
return getters;
}
});
}
delete store.__mockedGetters;
delete store.__gettersProxy;
delete store.__originalGetters;
};