-
Notifications
You must be signed in to change notification settings - Fork 68
/
Countdown.test.tsx
644 lines (536 loc) · 19.7 KB
/
Countdown.test.tsx
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
import * as React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import Countdown, { CountdownProps } from './Countdown';
import { calcTimeDelta, CountdownTimeDelta, formatTimeDelta } from './utils';
import { CountdownProps as LegacyCountdownProps } from './LegacyCountdown';
const timeDiff = 90110456;
const now = jest.fn(() => 1482363367071);
Date.now = now;
const defaultStats = {
total: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0,
completed: false,
};
describe('<Countdown />', () => {
jest.useFakeTimers();
let wrapper: ReactWrapper<CountdownProps, any, Countdown>;
let countdownDate: number;
const countdownMs = 10000;
beforeEach(() => {
Date.now = now;
const date = Date.now() + countdownMs;
const root = document.createElement('div');
countdownDate = date;
wrapper = mount(<Countdown date={date} />, { attachTo: root });
});
it('should render custom renderer output', () => {
wrapper = mount(
<Countdown
date={Date.now() + timeDiff}
renderer={props => (
<div>
{props.days}
{props.hours}
{props.minutes}
{props.seconds}
</div>
)}
/>
);
expect(wrapper).toMatchSnapshot();
});
it('should render and unmount component on countdown end', () => {
const zeroPadTime = 0;
class Completionist extends React.Component<any> {
componentDidMount() {}
render() {
return (
<div>
Completed! {this.props.name} {this.props.children}
</div>
);
}
}
let completionist;
Completionist.prototype.componentDidMount = jest.fn();
wrapper = mount(
<Countdown date={Date.now() + timeDiff} zeroPadTime={zeroPadTime}>
<Completionist
ref={el => {
completionist = el;
}}
name="master"
>
Another child
</Completionist>
</Countdown>
);
expect(Completionist.prototype.componentDidMount).not.toBeCalled();
expect(wrapper).toMatchSnapshot();
// Forward in time
wrapper.setProps({ date: 0 });
expect(wrapper.state().timeDelta.completed).toBe(true);
expect(wrapper.props().children!.type).toBe(Completionist);
expect(Completionist.prototype.componentDidMount).toBeCalled();
const computedProps = { ...wrapper.props() };
delete computedProps.children;
const obj = wrapper.instance();
const { timeDelta } = wrapper.state();
expect(completionist.props).toEqual({
countdown: {
...timeDelta,
api: obj.getApi(),
props: wrapper.props(),
formatted: formatTimeDelta(timeDelta, { zeroPadTime }),
},
name: 'master',
children: 'Another child',
});
expect(wrapper).toMatchSnapshot();
});
it('should render with daysInHours => true', () => {
wrapper = mount(<Countdown date={Date.now() + timeDiff} daysInHours />);
expect(wrapper).toMatchSnapshot();
});
it('should render with zeroPadDays => 3', () => {
wrapper = mount(<Countdown date={Date.now() + 10 * 86400 * 1000} zeroPadDays={3} />);
expect(wrapper).toMatchSnapshot();
});
it('should trigger onTick and onComplete callbacks', () => {
const onTick = jest.fn(stats => {
expect(stats).toEqual(calcTimeDelta(countdownDate));
});
const onComplete = jest.fn(stats => {
expect(stats.total).toEqual(0);
});
wrapper.setProps({ onTick, onComplete });
expect(onTick).not.toBeCalled();
// Forward 6s in time
now.mockReturnValue(countdownDate - 6000);
jest.runTimersToTime(6000);
expect(onTick.mock.calls.length).toBe(6);
expect(wrapper.state().timeDelta.total).toBe(6000);
wrapper.update();
expect(wrapper).toMatchSnapshot();
// Forward 3 more seconds
now.mockReturnValue(countdownDate - 1000);
jest.runTimersToTime(3000);
expect(onTick.mock.calls.length).toBe(9);
expect(wrapper.state().timeDelta.total).toBe(1000);
expect(wrapper.state().timeDelta.completed).toBe(false);
// The End: onComplete callback gets triggered instead of the onTick callback
now.mockReturnValue(countdownDate);
jest.runTimersToTime(1000);
expect(onTick.mock.calls.length).toBe(9);
expect(onTick).toBeCalledWith({
...defaultStats,
total: 1000,
seconds: 1,
});
expect(onComplete).toBeCalledTimes(1);
expect(onComplete).toBeCalledWith({ ...defaultStats, completed: true }, false);
expect(wrapper.state().timeDelta.completed).toBe(true);
});
it('should trigger various callbacks before onComplete is called', () => {
const calls: string[] = [];
const onStart = jest.fn().mockImplementation(() => calls.push('onStart'));
const onTick = jest.fn().mockImplementation(() => calls.push('onTick'));
const onComplete = jest.fn().mockImplementation(() => calls.push('onComplete'));
wrapper = mount(
<Countdown date={countdownDate} onStart={onStart} onTick={onTick} onComplete={onComplete} />
);
expect(calls).toEqual(['onStart']);
for (let i = 1; i <= 10; i++) {
now.mockReturnValue(countdownDate - countdownMs + i * 1000);
jest.runTimersToTime(1000);
}
expect(calls).toEqual(['onStart', ...new Array(9).fill('onTick'), 'onComplete']);
});
it('should trigger onComplete callback on start if date is in the past when countdown starts', () => {
const calls: string[] = [];
const onStart = jest.fn().mockImplementation(() => calls.push('onStart'));
const onTick = jest.fn().mockImplementation(() => calls.push('onTick'));
const onComplete = jest.fn().mockImplementation(() => calls.push('onComplete'));
countdownDate = Date.now() - 10000;
wrapper = mount(
<Countdown date={countdownDate} onStart={onStart} onTick={onTick} onComplete={onComplete} />
);
expect(onStart).toHaveBeenCalledTimes(1);
expect(onTick).not.toHaveBeenCalled();
expect(onComplete).toHaveBeenCalledTimes(1);
expect(onComplete).toBeCalledWith({ ...defaultStats, completed: true }, true);
expect(calls).toEqual(['onStart', 'onComplete']);
});
it('should run through the controlled component by updating the date prop', () => {
const root = document.createElement('div');
wrapper = mount(<Countdown date={1000} controlled />, { attachTo: root });
const obj = wrapper.instance();
const api = obj.getApi();
expect(obj.interval).toBeUndefined();
expect(wrapper.state().timeDelta.completed).toBe(false);
expect(api.isCompleted()).toBe(false);
wrapper.setProps({ date: 0 });
expect(wrapper.state().timeDelta.total).toBe(0);
expect(wrapper.state().timeDelta.completed).toBe(true);
expect(api.isCompleted()).toBe(true);
});
it('should only reset time delta state when date prop is changing', () => {
const root = document.createElement('div');
wrapper = mount(<Countdown date={1000} />, { attachTo: root });
const obj = wrapper.instance();
obj.setTimeDeltaState = jest.fn();
function mergeProps(partialProps: Partial<CountdownProps>): CountdownProps {
return { ...wrapper.props(), ...partialProps };
}
wrapper.setProps(mergeProps({ date: 500 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(1);
wrapper.setProps(mergeProps({ intervalDelay: 999 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(1);
wrapper.setProps(mergeProps({ date: 500 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(1);
wrapper.setProps(mergeProps({ precision: 3 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(1);
wrapper.setProps(mergeProps({ date: 750 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(2);
wrapper.setProps(mergeProps({ children: <div /> }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(2);
wrapper.setProps(mergeProps({ date: 1000 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(3);
});
it('should not (try to) set state after component unmount', () => {
expect(wrapper.state().timeDelta.completed).toBe(false);
now.mockReturnValue(countdownDate - 6000);
jest.runTimersToTime(6000);
expect(wrapper.state().timeDelta.total).toBe(6000);
wrapper.instance().mounted = false;
now.mockReturnValue(countdownDate - 3000);
jest.runTimersToTime(3000);
expect(wrapper.state().timeDelta.total).toBe(6000);
});
it('should set countdown status to STOPPED if a prop-update occurs that updates a completed countdown', () => {
wrapper = mount(<Countdown date={countdownDate} />);
const obj = wrapper.instance();
const api = obj.getApi();
expect(api.isStarted()).toBe(true);
wrapper.setProps({ date: countdownDate + 1000 });
expect(api.isStarted()).toBe(true);
wrapper.setProps({ date: 0 });
expect(api.isCompleted()).toBe(true);
wrapper.setProps({ date: countdownDate + 1000 });
expect(api.isStopped()).toBe(true);
});
it('should pause => start => pause => stop and restart countdown', () => {
const spies = {
onMount: jest.fn(),
onStart: jest.fn(),
onPause: jest.fn(),
onStop: jest.fn(),
};
wrapper = mount(<Countdown date={countdownDate} {...spies} />);
const obj = wrapper.instance();
const api = obj.getApi();
expect(obj.offsetStartTimestamp).toBe(0);
expect(obj.offsetTime).toBe(0);
expect(api.isStarted()).toBe(true);
expect(api.isPaused()).toBe(false);
expect(api.isStopped()).toBe(false);
expect(api.isCompleted()).toBe(false);
expect(spies.onMount).toHaveBeenCalledTimes(1);
expect(spies.onMount).toHaveBeenCalledWith({
completed: false,
total: 10000,
days: 0,
hours: 0,
minutes: 0,
seconds: 10,
milliseconds: 0,
});
expect(spies.onStart).toHaveBeenCalledTimes(1);
expect(spies.onPause).toHaveBeenCalledTimes(0);
expect(spies.onStop).toHaveBeenCalledTimes(0);
let runMs = 2000;
const nowBeforePause = countdownDate - (countdownMs - runMs);
now.mockReturnValue(nowBeforePause);
jest.runTimersToTime(runMs);
expect(wrapper.state().timeDelta.total).toBe(countdownMs - runMs);
api.pause();
expect(api.isStarted()).toBe(false);
expect(api.isPaused()).toBe(true);
expect(api.isStopped()).toBe(false);
expect(api.isCompleted()).toBe(false);
expect(spies.onMount).toHaveBeenCalledTimes(1);
expect(spies.onStart).toHaveBeenCalledTimes(1);
expect(spies.onPause).toHaveBeenCalledTimes(1);
expect(spies.onPause).toHaveBeenCalledWith({
completed: false,
total: 8000,
days: 0,
hours: 0,
minutes: 0,
seconds: 8,
milliseconds: 0,
});
expect(spies.onStop).toHaveBeenCalledTimes(0);
// Calling pause() a 2nd time while paused should return early
api.pause();
expect(api.isPaused()).toBe(true);
expect(spies.onPause).toHaveBeenCalledTimes(1);
runMs += 2000;
const pausedMs = 2000;
now.mockReturnValue(countdownDate - (countdownMs - runMs));
jest.runTimersToTime(runMs);
expect(countdownMs - runMs + pausedMs).toBe(8000);
expect(wrapper.state().timeDelta.total).toBe(8000);
expect(obj.offsetStartTimestamp).toBe(nowBeforePause);
expect(obj.offsetTime).toBe(0);
api.start();
expect(api.isStarted()).toBe(true);
expect(api.isPaused()).toBe(false);
expect(api.isStopped()).toBe(false);
expect(api.isCompleted()).toBe(false);
expect(spies.onMount).toHaveBeenCalledTimes(1);
expect(spies.onStart).toHaveBeenCalledTimes(2);
expect(spies.onStart).toHaveBeenCalledWith({
completed: false,
total: 8000,
days: 0,
hours: 0,
minutes: 0,
seconds: 8,
milliseconds: 0,
});
expect(spies.onPause).toHaveBeenCalledTimes(1);
expect(spies.onStop).toHaveBeenCalledTimes(0);
expect(wrapper.state().timeDelta.total).toBe(8000);
expect(obj.offsetStartTimestamp).toBe(0);
expect(obj.offsetTime).toBe(pausedMs);
runMs += 1000;
now.mockReturnValue(countdownDate - (countdownMs - runMs));
jest.runTimersToTime(runMs);
expect(countdownMs - runMs + pausedMs).toBe(7000);
expect(wrapper.state().timeDelta.total).toBe(7000);
expect(obj.offsetStartTimestamp).toBe(0);
expect(obj.offsetTime).toBe(pausedMs);
runMs += 1000;
now.mockReturnValue(countdownDate - (countdownMs - runMs));
jest.runTimersToTime(runMs);
api.pause();
expect(obj.offsetStartTimestamp).toBe(now());
expect(obj.offsetTime).toBe(2000);
expect(wrapper.state().timeDelta).toEqual({
completed: false,
total: 6000,
days: 0,
hours: 0,
minutes: 0,
seconds: 6,
milliseconds: 0,
});
runMs += 1000;
now.mockReturnValue(countdownDate - (countdownMs - runMs));
jest.runTimersToTime(runMs);
api.stop();
expect(obj.offsetStartTimestamp).toBe(now());
expect(obj.offsetTime).toBe(runMs);
expect(api.isStarted()).toBe(false);
expect(api.isPaused()).toBe(false);
expect(api.isStopped()).toBe(true);
expect(api.isCompleted()).toBe(false);
expect(spies.onMount).toHaveBeenCalledTimes(1);
expect(spies.onStart).toHaveBeenCalledTimes(2);
expect(spies.onPause).toHaveBeenCalledTimes(2);
expect(spies.onStop).toHaveBeenCalledTimes(1);
expect(spies.onStop).toHaveBeenCalledWith({
completed: false,
total: 10000,
days: 0,
hours: 0,
minutes: 0,
seconds: 10,
milliseconds: 0,
});
// Calling stop() a 2nd time while stopped should return early
api.stop();
expect(api.isStopped()).toBe(true);
expect(spies.onStop).toHaveBeenCalledTimes(1);
api.start();
runMs += 10000;
now.mockReturnValue(countdownDate + runMs + pausedMs);
jest.runTimersToTime(countdownMs + pausedMs);
expect(wrapper.state().timeDelta.total).toBe(0);
expect(wrapper.state().timeDelta.completed).toBe(true);
expect(api.isCompleted()).toBe(true);
expect(obj.offsetStartTimestamp).toBe(0);
expect(obj.offsetTime).toBe(7000);
expect(spies.onMount).toHaveBeenCalledTimes(1);
expect(spies.onStart).toHaveBeenCalledTimes(3);
expect(spies.onPause).toHaveBeenCalledTimes(2);
expect(spies.onStop).toHaveBeenCalledTimes(1);
});
it('should not auto start countdown', () => {
const spies = {
onStart: jest.fn(),
};
wrapper = mount(<Countdown date={countdownDate} autoStart={false} {...spies} />);
const obj = wrapper.instance();
const api = obj.getApi();
expect(spies.onStart).toHaveBeenCalledTimes(0);
expect(api.isStarted()).toBe(false);
expect(api.isPaused()).toBe(false);
expect(api.isStopped()).toBe(true);
expect(api.isCompleted()).toBe(false);
expect(obj).toEqual(
expect.objectContaining({
offsetStartTimestamp: countdownDate - countdownMs,
offsetTime: 0,
})
);
api.start();
expect(spies.onStart).toHaveBeenCalledTimes(1);
expect(api.isStarted()).toBe(true);
expect(api.isPaused()).toBe(false);
expect(api.isStopped()).toBe(false);
expect(api.isCompleted()).toBe(false);
expect(obj).toEqual(
expect.objectContaining({
offsetStartTimestamp: 0,
offsetTime: 0,
})
);
// Calling start() a 2nd time while started should return early
api.start();
expect(spies.onStart).toHaveBeenCalledTimes(1);
});
it('should continuously call the renderer if date is in the future', () => {
const renderer = jest.fn(() => <div />);
wrapper = mount(<Countdown date={countdownDate} renderer={renderer} />);
expect(renderer).toHaveBeenCalledTimes(2);
// Forward 1s
now.mockReturnValue(countdownDate - 9000);
jest.runTimersToTime(1000);
expect(renderer).toHaveBeenCalledTimes(3);
// Forward 2s
now.mockReturnValue(countdownDate - 8000);
jest.runTimersToTime(1000);
expect(renderer).toHaveBeenCalledTimes(4);
expect(wrapper.state().timeDelta.total).toBe(8000);
expect(wrapper.state().timeDelta.completed).toBe(false);
});
it('should stop immediately if date is in the past', () => {
const renderer = jest.fn(() => <div />);
countdownDate = Date.now() - 10000;
wrapper = mount(<Countdown date={countdownDate} renderer={renderer} />);
expect(renderer).toHaveBeenCalledTimes(2);
// Forward 1s
now.mockReturnValue(countdownDate - 9000);
jest.runTimersToTime(1000);
expect(renderer).toHaveBeenCalledTimes(2);
// Forward 2s
now.mockReturnValue(countdownDate - 8000);
jest.runTimersToTime(1000);
expect(renderer).toHaveBeenCalledTimes(2);
expect(wrapper.state().timeDelta.total).toBe(0);
expect(wrapper.state().timeDelta.completed).toBe(true);
});
it('should not stop the countdown and go into overtime', () => {
const onTick = jest.fn();
wrapper = mount(
<Countdown date={countdownDate} overtime={true} onTick={onTick}>
<div>Completed? Overtime!</div>
</Countdown>
);
const obj = wrapper.instance();
const api = obj.getApi();
// Forward 9s
now.mockReturnValue(countdownDate - 1000);
jest.runTimersToTime(9000);
expect(wrapper.text()).toMatchInlineSnapshot(`"00:00:00:01"`);
expect(onTick).toHaveBeenCalledTimes(9);
// Forward 1s
now.mockReturnValue(countdownDate);
jest.runTimersToTime(1000);
expect(wrapper.text()).toMatchInlineSnapshot(`"00:00:00:00"`);
expect(onTick).toHaveBeenCalledTimes(10);
expect(wrapper.state().timeDelta.total).toBe(0);
expect(wrapper.state().timeDelta.completed).toBe(true);
expect(api.isCompleted()).toBe(false);
// Forward 1s (overtime)
now.mockReturnValue(countdownDate + 1000);
jest.runTimersToTime(1000);
expect(wrapper.text()).toMatchInlineSnapshot(`"-00:00:00:01"`);
expect(onTick).toHaveBeenCalledTimes(11);
expect(wrapper.state().timeDelta.total).toBe(-1000);
expect(wrapper.state().timeDelta.completed).toBe(true);
expect(api.isCompleted()).toBe(false);
});
describe('legacy mode', () => {
class LegacyCountdownOverlay extends React.Component<LegacyCountdownProps> {
render() {
return <div>{this.props.count}</div>;
}
}
it('should render legacy countdown', () => {
wrapper = mount(
<Countdown count={3}>
<LegacyCountdownOverlay />
</Countdown>
);
expect(wrapper.find('div').text()).toBe('3');
});
it('should render legacy countdown without count prop', () => {
wrapper = mount(
<Countdown>
<LegacyCountdownOverlay />
</Countdown>
);
expect(wrapper.find('div').text()).toBe('3');
});
it('should render null without children', () => {
wrapper = mount(<Countdown count={3}></Countdown>);
expect(wrapper.html()).toBe('');
wrapper.setProps({});
wrapper.unmount();
});
it('should allow adding time in seconds', () => {
const ref = React.createRef<Countdown>();
wrapper = mount(
<>
<Countdown ref={ref} count={3}>
<LegacyCountdownOverlay />
</Countdown>
</>
);
expect(wrapper.find('div').text()).toBe('3');
ref && ref.current && ref.current.addTime(2);
jest.runOnlyPendingTimers();
wrapper.update();
expect(wrapper.find('div').text()).toBe('4');
});
it('should trigger onComplete callback when count reaches 0', () => {
const ref = React.createRef<Countdown>();
const onComplete = jest.fn();
wrapper = mount(
<>
<Countdown ref={ref} count={3} onComplete={onComplete}>
<LegacyCountdownOverlay />
</Countdown>
</>
);
expect(onComplete).not.toHaveBeenCalled();
ref && ref.current && ref.current.addTime(-2);
jest.runOnlyPendingTimers();
wrapper.update();
expect(onComplete).toHaveBeenCalled();
expect(wrapper.find('div').text()).toBe('1');
});
});
afterEach(() => {
try {
wrapper.detach();
} catch (e) {}
});
});