-
Notifications
You must be signed in to change notification settings - Fork 0
/
vuex-snapshot.js
469 lines (376 loc) · 10.9 KB
/
vuex-snapshot.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
'use strict';
const find = (arr, matchFn) => {
for(let i = 0; i < arr.length; ++i) {
if(matchFn(arr[i])) return arr[i]
}
};
const useGlobally = (name, value) => {
window[name] = value;
};
const makeSuffix = () => {
const suffix = () => suffix.num > 1 ? '[' + suffix.num.toString() + ']' : '';
suffix.num = 1;
suffix.next = () => ++suffix.num;
return suffix
};
const RealPromise = Promise;
const entries = [];
const register = ({name, promise, payload, resolve, reject}) => {
const entry = {
payload,
promise,
resolve,
reject,
called: false
};
// make sure name is unique
const suffix = makeSuffix();
while(find(entries, e => e.name === name + suffix())) suffix.next();
entry.name = name + suffix();
entries.push(entry);
};
const trigger = ({name, type, payload}) => {
const suffix = makeSuffix();
while(find(entries, e => e.name === name + suffix() && e.called)) suffix.next();
const entry = find(entries, e => e.name === name + suffix());
return new RealPromise((resolve, reject) => {
if(typeof entry === 'undefined') {
reject(new Error(`vuex-snapshot: did not find ${name + suffix()} that wasn't already resolved or rejected`));
}
entry[type](payload);
entry.called = true;
RealPromise.resolve().then(resolve); //this would happen right after entry's promise resolutions
})
};
const ensureAbsence = (promise) => {
for(let i = 0; i < entries.length; ++i) {
if(entries[i].promise === promise) {
entries.splice(i, 1);
}
}
};
const reset = () => entries.length = 0;
var timetable = {
register,
trigger,
reset,
entries,
ensureAbsence,
}
const RealPromise$1 = Promise;
class MockPromise extends RealPromise$1 {
/**
* Named promise that can be resolved manually and properly serialized
* and registers it in timetable
* @param {Function} cb
* @param {string} name
*/
constructor(cb, name='Promise') {
let resolveTrigger;
let rejectTrigger;
// name-only construction
if(typeof cb === 'string') {
name = cb;
cb = () => {};
}
const cbProxy = (resolve, reject) => {
resolveTrigger = resolve;
rejectTrigger = reject;
cb(resolve, reject);
};
super(cbProxy);
this.name = name;
this.resolve = resolveTrigger;
this.reject = rejectTrigger;
timetable.register({
name,
promise: this,
payload: cb,
resolve: resolveTrigger,
reject: rejectTrigger
});
}
}
const useMock = () => useGlobally('Promise', MockPromise);
const useReal = () => useGlobally('Promise', RealPromise$1);
const RealPromise$2 = Promise;
const realFetch = window.fetch;
/**
* Creates mock fetch that can be resolved manually and properly serialized
* and registers it in timetable
* @param {string} url
* @param {any} init
* @returns {Promise}
*/
const mockFetch = (url, init) => {
let resolveTrigger;
let rejectTrigger;
const cbProxy = (resolve, reject) => {
resolveTrigger = resolve;
rejectTrigger = reject;
};
const simulation = new RealPromise$2(cbProxy);
simulation.name = url;
simulation.resolve = resolveTrigger;
simulation.reject = rejectTrigger;
timetable.register({
name: url,
promise: simulation,
payload: init,
resolve: resolveTrigger,
reject: rejectTrigger
});
return simulation
};
const useMock$1 = () => useGlobally('fetch', mockFetch);
const useReal$1 = () => useGlobally('fetch', realFetch);
class Snapshot {
constructor() {
this.value = [];
this.frozen = false;
this.add = this.add.bind(this);
this.freeze = this.freeze.bind(this);
this.unfreeze = this.unfreeze.bind(this);
}
add(message, payload) {
if(this.frozen) return
const entry = {};
entry.message = message;
if(typeof payload !== 'undefined') entry.payload = payload;
this.value.push(entry);
}
freeze() {
this.frozen = true;
}
unfreeze() {
this.frozen = false;
}
}
const RealPromise$3 = Promise;
const normalizeResolution = resolution => {
const normalResolution = {
name: '',
type: 'resolve',
payload: undefined,
};
// string constructor
if(typeof resolution === 'string' || resolution instanceof String) {
normalResolution.name = resolution;
return normalResolution
}
// object constructor, errors are duplicated because they are likely to occur in promises
if(typeof resolution.name !== 'undefined') {
normalResolution.name = resolution.name;
} else {
throw new Error('vuex-snapshot: INPUT ERROR resolution must have a name')
}
if(resolution.type) {
if(['resolve', 'reject'].indexOf(resolution.type) !== -1) {
normalResolution.type = resolution.type;
} else {
throw new Error('vuex-snapshot: INPUT ERROR resolution type must be'
+ 'either "resolve" or "reject"')
}
}
if(typeof resolution.payload !== 'undefined') {
normalResolution.payload = resolution.payload;
}
return normalResolution
};
const simualteResolution = (resolution, snapshot, timetable) => {
snapshot.add(`RESOLUTION: ${resolution.name} -> ${resolution.type}`, resolution.payload);
return timetable.trigger(resolution)
};
// for testablility
const lib = {
simualteResolution,
normalizeResolution,
};
const simualteResolutions = (resolutions, snapshot, timetable, options) => {
return new RealPromise$3((resolveSimulation, rejectSimulation) => {
const normalResolutions = resolutions.map(lib.normalizeResolution);
if(options.autoResolve) {
let count = 0; // to break infinite loops
// finds next uncalled entry and calls it
const autoSimulationLoop = () => {
count++;
const nextEntry = find(timetable.entries, e => !e.called);
if(nextEntry && count < 1000) {
const nextResolution = lib.normalizeResolution(nextEntry.name);
lib.simualteResolution(nextResolution, snapshot, timetable)
.then(autoSimulationLoop)
.catch(rejectSimulation);
} else {
resolveSimulation();
}
};
autoSimulationLoop();
} else {
// simulates given resolution and queues the next until all are simulated
const simulationLoop = (idx=0) => {
if(idx === normalResolutions.length) {
resolveSimulation();
}
else {
lib.simualteResolution(normalResolutions[idx], snapshot, timetable)
.then(() => simulationLoop(idx + 1))
.catch(rejectSimulation);
}
};
simulationLoop();
}
})
};
const RealPromise$4 = Promise;
const makeCallSnapper = (snapshot, type, cb) => {
const snapper = (name, payload) => {
snapshot.add(`${type}: ${name}`, payload);
return cb(name, payload, snapper.proxies)
};
return snapper
};
/**
* @typedef {{name:string, type: ("resolve" | "reject"), payload}} Resolution
*/
/**
* Takes snapshot of action's evaluation
* @param {Function} action action to test
* @param {{state, getters, commit: Function, dispatch: Function, payload}} mocks arguments passed to the action, payload is the second argument
* @param {[(string | Resolution)]} resolutions
* @param {{autoResolve: Boolean, snapEnv: Boolean, allowManualActionResolution: Boolean}} options
* @returns {(string | Promise<string>)}
*/
const snapAction = (action, mocks, resolutions, options, snapshot) => {
const mockCommit = makeCallSnapper(snapshot, 'COMMIT', mocks.commit);
const mockDispatch = makeCallSnapper(snapshot, 'DISPATCH', mocks.dispatch);
const proxies = {
commit: mockCommit,
dispatch: mockDispatch
};
mockCommit.proxies = proxies;
mockDispatch.proxies = proxies;
if(options.snapEnv) {
snapshot.add('DATA MOCKS', {
state: mocks.state,
getters: mocks.getters
});
snapshot.add('ACTION CALL', mocks.payload);
}
const actionReturn = action({
commit: mockCommit,
dispatch: mockDispatch,
state: mocks.state,
getters: mocks.getters
}, mocks.payload);
if(typeof actionReturn !== 'undefined' && actionReturn instanceof Promise) {
// action is async
if(!options.allowManualActionResolution) {
timetable.ensureAbsence(actionReturn);
}
return new RealPromise$4((resolve, reject) => {
actionReturn
.then(payload => {
snapshot.add('ACTION RESOLVED', payload);
snapshot.freeze();
resolve(snapshot.value);
})
.catch(payload => {
snapshot.add('ACTION REJECTED', payload);
snapshot.freeze();
resolve(snapshot.value);
});
simualteResolutions(resolutions, snapshot, timetable, options)
.then(() => {
// this is needed to let action to resolve first
setTimeout(() => {
snapshot.add('ACTION DID NOT RESOLVE');
resolve(snapshot.value);
}, 0);
})
.catch(err => {
reject({
err,
run: snapshot.value
});
});
})
} else {
// action is sync
return snapshot.value
}
};
/**
* @namespace
* @property {Boolean} autoResolve resolve all MockPromises and fetches in order they were created
* @property {Boolean} snapEnv include state, getters and payload into snapshot
* @property {Boolean} allowManualActionResolution simaulation can now resolve action'sReturn value
*/
const options = {
autoResolve: false,
snapEnv: false,
allowManualActionResolution: false
};
// they are likely to stay flat
const defaults = Object.assign({}, options);
const reset$1 = () => Object.assign(options, defaults);
reset$1();
var config = {
options,
reset: reset$1
}
/**
* Resets config and timetable
*/
const reset$2 = () => {
config.reset();
timetable.reset();
useReal();
useReal$1();
};
/**
* @typedef {{name:string, type: ("resolve" | "reject"), payload}} Resolution
*/
/**
* Takes snapshot of action's evaluation
* @param {Function} action action to test
* @param {{state, getters, commit: Function, dispatch: Function, payload}} mocks arguments passed to the action, payload is the second argument
* @param {[(string | Resolution)]} resolutions
* @returns {(Array | Promise<Array>)}
*/
const snapAction$1 = (action, mocks={}, resolutions=[], snapshot=new Snapshot()) => {
if(Array.isArray(mocks)) {
resolutions = mocks;
mocks = {};
}
const commit = mocks.commit || (() => {});
const dispatch = mocks.dispatch || (() => {});
return snapAction(
action,
{
payload: mocks.payload,
state: mocks.state,
getters: mocks.getters,
commit,
dispatch
},
resolutions,
config.options,
snapshot
)
};
var index = {
snapAction: snapAction$1,
reset: reset$2,
timetable,
resetTimetable: timetable.reset,
config: config.options,
resetConfig: config.reset,
Snapshot,
mockFetch: mockFetch,
useMockFetch: useMock$1,
useRealFetch: useReal$1,
MockPromise: MockPromise,
useMockPromise: useMock,
useRealPromise: useReal,
}
module.exports = index;