-
Notifications
You must be signed in to change notification settings - Fork 187
/
Copy pathindex.spec.js
780 lines (657 loc) · 21.6 KB
/
index.spec.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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
/* eslint no-unused-vars: 0, no-unused-expressions: 0, no-shadow: 0 */
import Bluebird from 'bluebird';
import { createStore, applyMiddleware } from 'redux';
import configureStore from 'redux-mock-store';
import promiseMiddleware, { PENDING, FULFILLED, REJECTED } from '../src/index';
describe('Redux Promise Middleware:', () => {
let store;
let promiseAction;
let pendingAction;
let fulfilledAction;
let rejectedAction;
const promiseValue = 'foo';
const promiseReason = new Error('bar');
const customPrefix = 'CUSTOM';
const optimisticUpdateData = { foo: true };
const metaData = { bar: true };
const lastMiddlewareData = { baz: true };
const defaultPromiseAction = {
type: 'ACTION',
payload: new Promise(resolve => resolve(promiseValue))
};
const defaultPendingAction = {
type: `${defaultPromiseAction.type}_PENDING`
};
const defaultFulfilledAction = {
type: `${defaultPromiseAction.type}_FULFILLED`,
payload: promiseValue
};
const defaultRejectedAction = {
type: `${defaultPromiseAction.type}_REJECTED`,
error: true,
payload: promiseReason
};
const nextHandler = promiseMiddleware();
it('must export correct default promise status', () => {
chai.assert.equal(PENDING, 'PENDING');
chai.assert.equal(FULFILLED, 'FULFILLED');
chai.assert.equal(REJECTED, 'REJECTED');
});
it('must return a function to handle next', () => {
chai.assert.isFunction(nextHandler);
chai.assert.strictEqual(nextHandler.length, 1);
});
/**
* Make two fake middleware to surround promiseMiddleware in chain,
* Give both of them a spy property to assert on their usage
*/
// first middleware mimics redux-thunk
function firstMiddlewareThunk(ref, next) {
this.spy = sinon.spy((action) => {
if (typeof action === 'function') {
return action(ref.dispatch, ref.getState);
}
return next(action);
});
return this.spy;
}
// final middleware returns the action merged with dummy data
function lastMiddlewareModifies(next) {
this.spy = sinon.spy((action) => {
next(action);
return {
...action,
...lastMiddlewareData
};
});
return this.spy;
}
/*
* Function for creating a dumb store using fake middleware stack
*/
const makeStore = (config) => applyMiddleware(
ref => next => firstMiddlewareThunk.call(firstMiddlewareThunk, ref, next),
promiseMiddleware(config),
() => next => lastMiddlewareModifies.call(lastMiddlewareModifies, next)
)(createStore)(() => null);
beforeEach(() => {
store = makeStore();
});
afterEach(() => {
firstMiddlewareThunk.spy.reset();
lastMiddlewareModifies.spy.reset();
});
context('When action is not a promise:', () => {
const mockAction = { type: 'ACTION' };
it('invokes next with the action', () => {
store.dispatch(mockAction);
expect(lastMiddlewareModifies.spy).to.have.been.calledWith(mockAction);
});
it('returns the return from next middleware', () => {
expect(store.dispatch(mockAction)).to.eql({
...mockAction,
...lastMiddlewareData
});
});
it('does not dispatch any other actions', () => {
const mockStore = configureStore([promiseMiddleware()]);
const store = mockStore({});
store.dispatch(mockAction);
expect([mockAction]).to.eql(store.getActions());
});
});
context('When action has promise payload:', () => {
beforeEach(() => {
promiseAction = defaultPromiseAction;
pendingAction = defaultPendingAction;
rejectedAction = defaultRejectedAction;
fulfilledAction = defaultFulfilledAction;
});
afterEach(() => {
promiseAction = defaultPromiseAction;
pendingAction = defaultPendingAction;
rejectedAction = defaultRejectedAction;
fulfilledAction = defaultFulfilledAction;
});
/**
* This tests if the middleware dispatches a pending action when the payload
* property has a Promise object as the value. This is considered an "implicit"
* promise payload.
*/
it('dispatches a pending action for implicit promise payload', () => {
store.dispatch(promiseAction);
expect(lastMiddlewareModifies.spy).to.have.been.calledWith(pendingAction);
});
/**
* This tests if the middleware dispatches a pending action
* when the payload has a `promise` property with a Promise object
* as the value. This is considered an "explicit" promise payload because
* the `promise` property explicitly describes the value.
*/
it('dispatches a pending action for explicit promise payload', () => {
store.dispatch({
type: promiseAction.type,
payload: {
promise: promiseAction.payload
}
});
expect(lastMiddlewareModifies.spy).to.have.been.calledWith(pendingAction);
});
/**
* If the promise action is dispatched with a data property, that property and value
* must be included in the pending action the middleware dispatches. This property
* is used for optimistic updates.
*/
it('pending action optionally contains optimistic update payload from data property', () => {
store.dispatch({
type: promiseAction.type,
payload: {
promise: promiseAction.payload,
data: optimisticUpdateData
}
});
expect(lastMiddlewareModifies.spy).to.have.been.calledWith({
...pendingAction,
payload: optimisticUpdateData
});
});
it('pending action optionally contains falsy optimistic update payload', () => {
store.dispatch({
type: promiseAction.type,
payload: {
promise: promiseAction.payload,
data: 0
}
});
expect(lastMiddlewareModifies.spy).to.have.been.calledWith({
...pendingAction,
payload: 0
});
});
/**
* If the promise action is dispatched with a meta property, the meta property
* and value must be included in the pending action.
*/
it('pending action does contain meta property if included', () => {
store.dispatch(Object.assign({}, promiseAction, {
meta: metaData
}));
expect(lastMiddlewareModifies.spy).to.have.been.calledWith(
Object.assign({}, pendingAction, {
meta: metaData
})
);
});
it('pending action does contain falsy meta property if included', () => {
store.dispatch(Object.assign({}, promiseAction, {
meta: 0
}));
expect(lastMiddlewareModifies.spy).to.have.been.calledWith(
Object.assign({}, pendingAction, {
meta: 0
})
);
});
/**
* The middleware should allow global custom action types included
* in the config when the middleware is constructed.
*/
it('allows global customisation of action type suffixes', () => {
store = makeStore({ promiseTypeSuffixes: [customPrefix, '', ''] });
store.dispatch(promiseAction);
expect(lastMiddlewareModifies.spy).to.have.been.calledWith(
Object.assign({}, pendingAction, {
type: `${promiseAction.type}_${customPrefix}`
})
);
});
/**
* The middleware should allow global custom action type delimiter included
* in the config when the middleware is constructed.
*/
it('allows global customisation of action type delimiter', done => {
store = makeStore({
promiseTypeDelimiter: '/'
});
fulfilledAction = {
type: `${promiseAction.type}/FULFILLED`,
payload: promiseValue
};
const actionDispatched = store.dispatch(promiseAction);
actionDispatched.then(({ value, action }) => {
expect(action).to.eql(fulfilledAction);
expect(value).to.eql(promiseValue);
done();
});
});
/**
* The middleware should be backward compatible and use '_' as separator by default.
*/
it('uses default separator with empty config (backward compatibility)', done => {
store = makeStore({});
fulfilledAction = {
type: `${promiseAction.type}_FULFILLED`,
payload: promiseValue
};
const actionDispatched = store.dispatch(promiseAction);
actionDispatched.then(({ value, action }) => {
expect(action).to.eql(fulfilledAction);
expect(value).to.eql(promiseValue);
done();
});
});
});
context('When promise is fulfilled:', () => {
beforeEach(() => {
promiseAction = {
type: defaultPromiseAction.type,
payload: new Promise(resolve => resolve(promiseValue))
};
fulfilledAction = defaultFulfilledAction;
});
/**
* This test ensures the original promise object is not mutated. In the case
* a promise library is used, adding methods to the promise class, the
* middleware should not remove those methods.
*/
it('propagates the original promise', done => {
const actionDispatched = store.dispatch({
type: defaultPromiseAction.type,
payload: Bluebird.resolve(promiseValue)
});
// Expect the promise returned has orginal methods available
expect(actionDispatched.any).to.be.a('function');
actionDispatched.then(
({ value, action }) => {
expect(value).to.eql(promiseValue);
expect(action).to.eql(fulfilledAction);
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
context('When resolve reason is null:', () => {
const nullResolveAction = {
type: defaultPromiseAction.type,
payload: Promise.resolve(null)
};
it('resolved action is dispatched', done => {
const actionDispatched = store.dispatch(nullResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(action).to.eql({
type: `${nullResolveAction.type}_FULFILLED`
});
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
it('promise returns `null` value', done => {
const actionDispatched = store.dispatch(nullResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(value).to.be.null;
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
/**
* If the resolved promise value is null, then there should not be a
* payload on the dispatched resolved action.
*/
it('resolved action `payload` property is undefined', done => {
const actionDispatched = store.dispatch(nullResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(action.payload).to.be.undefined;
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
});
context('When resolve reason is false:', () => {
const falseResolveAction = {
type: defaultPromiseAction.type,
payload: Promise.resolve(false)
};
it('resolved action is dispatched', done => {
const actionDispatched = store.dispatch(falseResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(action).to.eql({
type: `${falseResolveAction.type}_FULFILLED`,
payload: false
});
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
it('promise returns `false` value', done => {
const actionDispatched = store.dispatch(falseResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(value).to.be.false;
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
/**
* If the resolved promise value is false, then there should still be a
* payload on the dispatched resolved action.
*/
it('resolved action `payload` property is false', done => {
const actionDispatched = store.dispatch(falseResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(action.payload).to.be.false;
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
});
context('When resolve reason is zero:', () => {
const zeroResolveAction = {
type: defaultPromiseAction.type,
payload: Promise.resolve(0)
};
it('resolved action is dispatched', done => {
const actionDispatched = store.dispatch(zeroResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(action).to.eql({
type: `${zeroResolveAction.type}_FULFILLED`,
payload: 0
});
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
it('promise returns `0` value', done => {
const actionDispatched = store.dispatch(zeroResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(value).to.eq(0);
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
/**
* If the resolved promise value is zero, then there should still be a
* payload on the dispatched resolved action.
*/
it('resolved action `payload` property is zero', done => {
const actionDispatched = store.dispatch(zeroResolveAction);
actionDispatched.then(
({ value, action }) => {
expect(action.payload).to.eq(0);
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
});
it('persists `meta` property from original action', async () => {
await store.dispatch({
type: promiseAction.type,
payload: promiseAction.payload,
meta: metaData
});
expect(lastMiddlewareModifies.spy).to.have.been.calledWith({
type: `${promiseAction.type}_FULFILLED`,
payload: promiseValue,
meta: metaData
});
});
it('promise returns `value` and `action` as parameters', done => {
const actionDispatched = store.dispatch({
type: defaultPromiseAction.type,
payload: Promise.resolve(promiseValue)
});
actionDispatched.then(
({ value, action }) => {
expect(value).to.eql(promiseValue);
expect(action).to.eql(fulfilledAction);
done();
},
() => {
expect(true).to.equal(false); // Expect this is not called
}
);
});
it('allows global customisation of fulfilled action `type`', done => {
store = makeStore({
promiseTypeSuffixes: ['', customPrefix, '']
});
fulfilledAction = {
type: `${promiseAction.type}_${customPrefix}`,
payload: promiseValue
};
const actionDispatched = store.dispatch(promiseAction);
actionDispatched.then(({ value, action }) => {
expect(action).to.eql(fulfilledAction);
expect(value).to.eql(promiseValue);
done();
});
});
});
context('When using async functions:', () => {
it('supports async function as payload.promise', async () => {
const resolvedValue = 'FOO_DATA';
const { value, action } = await store.dispatch({
type: 'FOO',
payload: {
async promise() {
return resolvedValue;
}
}
});
const callArgs = lastMiddlewareModifies.spy.getCalls().map(x => x.args[0]);
expect(lastMiddlewareModifies.spy.callCount).to.eql(2);
expect(callArgs[0]).to.eql({
type: 'FOO_PENDING'
});
expect(callArgs[1]).to.eql({
type: 'FOO_FULFILLED',
payload: resolvedValue
});
});
it('supports async function as payload', async () => {
const resolvedValue = 'FOO_DATA';
const { value, action } = await store.dispatch({
type: 'FOO',
async payload() {
return resolvedValue;
}
});
const callArgs = lastMiddlewareModifies.spy.getCalls().map(x => x.args[0]);
expect(lastMiddlewareModifies.spy.callCount).to.eql(2);
expect(callArgs[0]).to.eql({
type: 'FOO_PENDING',
});
expect(callArgs[1]).to.eql({
type: 'FOO_FULFILLED',
payload: resolvedValue
});
});
it('supports optimistic updates', async () => {
const resolvedValue = 'FOO_DATA';
const data = {
foo: 1,
bar: 1,
baz: 3
};
const { value, action } = await store.dispatch({
type: 'FOO',
payload: {
data,
async promise() {
return resolvedValue;
}
}
});
const callArgs = lastMiddlewareModifies.spy.getCalls().map(x => x.args[0]);
expect(lastMiddlewareModifies.spy.callCount).to.eql(2);
expect(callArgs[0]).to.eql({
type: 'FOO_PENDING',
payload: data
});
expect(callArgs[1]).to.eql({
type: 'FOO_FULFILLED',
payload: resolvedValue
});
});
it('supports rejected async functions', async () => {
const error = new Error(Math.random().toString());
try {
await store.dispatch({
type: 'FOO',
async payload() {
throw error;
}
});
throw new Error('Should not get here.');
} catch (err) {
const callArgs = lastMiddlewareModifies.spy.getCalls().map(x => x.args[0]);
expect(lastMiddlewareModifies.spy.callCount).to.eql(2);
expect(callArgs[0]).to.eql({
type: 'FOO_PENDING',
});
expect(callArgs[1]).to.eql({
type: 'FOO_REJECTED',
error: true,
payload: error
});
}
});
it('handles synchronous functions', () => {
const resolvedValue = 'FOO_DATA';
const metaValue = {
foo: 'foo'
};
store.dispatch({
type: 'FOO',
meta: metaValue,
payload() {
return resolvedValue;
}
});
const callArgs = lastMiddlewareModifies.spy.getCalls().map(x => x.args[0]);
expect(lastMiddlewareModifies.spy.callCount).to.eql(1);
expect(callArgs[0]).to.eql({
type: 'FOO',
meta: metaValue,
payload: resolvedValue
});
});
});
context('When promise is rejected:', () => {
beforeEach(() => {
promiseAction = {
type: defaultPromiseAction.type,
payload: new Promise(() => {
throw promiseReason;
})
};
rejectedAction = defaultRejectedAction;
});
it('errors can be caught with `catch`', () => {
const actionDispatched = store.dispatch(promiseAction);
return actionDispatched
.then(() => expect(true).to.equal(false))
.catch(error => {
expect(error).to.be.instanceOf(Error);
});
});
it('errors can be caught with `then`', () => {
const actionDispatched = store.dispatch(promiseAction);
return actionDispatched.then(
() => expect(true).to.equal(false),
error => {
expect(error).to.be.instanceOf(Error);
expect(error.message).to.equal(promiseReason.message);
}
);
});
it('rejected action `error` property is true', () => {
const mockStore = configureStore([
promiseMiddleware(),
]);
const store = mockStore({});
return store.dispatch(promiseAction).catch(() => {
const rejectedAction = store.getActions()[1];
expect(rejectedAction.error).to.be.true;
});
});
it('rejected action `payload` property is original rejected instance of Error', () => {
const baseErrorMessage = 'error';
const baseError = new Error(baseErrorMessage);
const store = configureStore([
promiseMiddleware(),
])({});
return store.dispatch({
type: defaultPromiseAction.type,
payload: Promise.reject(baseError)
}).catch(() => {
const rejectedAction = store.getActions()[1];
expect(rejectedAction.payload).to.be.equal(baseError);
expect(rejectedAction.payload.message).to.be.equal(baseErrorMessage);
});
});
it('promise returns original rejected instance of Error', () => {
const baseErrorMessage = 'error';
const baseError = new Error(baseErrorMessage);
const actionDispatched = store.dispatch({
type: defaultPromiseAction.type,
payload: Promise.reject(baseError)
});
return actionDispatched.catch(error => {
expect(error).to.be.equal(baseError);
expect(error.message).to.be.equal(baseErrorMessage);
});
});
it('allows global customisation of rejected action `type`', () => {
const mockStore = configureStore([
promiseMiddleware({
promiseTypeSuffixes: ['', '', customPrefix]
}),
]);
const expectedRejectAction = {
type: `${promiseAction.type}_${customPrefix}`,
error: rejectedAction.error,
payload: rejectedAction.payload,
};
const store = mockStore({});
return store.dispatch(promiseAction).catch(() => {
expect(store.getActions()).to.include(expectedRejectAction);
});
});
});
});