node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
timer.unit.test.js
(2506B)
1 import timer from '../src/utils/timer.js';
2 import { jest } from '@jest/globals';
3
4 describe('Timer', () => {
5 it('nextIntervalAt before interval', () => {
6 setTime('2024-01-01T00:00:14.999Z');
7
8 const { nextIntervalAt } = timer({
9 createdAt: new Date('2024-01-01T00:00:00Z'),
10 expiresAt: new Date('2024-01-01T01:00:00Z'),
11 gameIntervalInSeconds: 15,
12 });
13
14 const actual = nextIntervalAt.toISOString();
15 expect(actual).toBe('2024-01-01T00:00:15.000Z');
16 });
17
18 it('nextIntervalAt at interval', () => {
19 setTime('2024-01-01T00:00:15.000Z');
20
21 const { nextIntervalAt } = timer({
22 createdAt: new Date('2024-01-01T00:00:00Z'),
23 expiresAt: new Date('2024-01-01T01:00:00Z'),
24 gameIntervalInSeconds: 15,
25 });
26
27 const actual = nextIntervalAt.toISOString();
28 expect(actual).toBe('2024-01-01T00:00:15.000Z');
29 });
30
31 it('nextIntervalAt after interval', () => {
32 setTime('2024-01-01T00:00:15.001Z');
33
34 const { nextIntervalAt } = timer({
35 createdAt: new Date('2024-01-01T00:00:00Z'),
36 expiresAt: new Date('2024-01-01T01:00:00Z'),
37 gameIntervalInSeconds: 15,
38 });
39
40 const actual = nextIntervalAt.toISOString();
41 expect(actual).toBe('2024-01-01T00:00:30.000Z');
42 });
43
44 it('nextIntervalInMillis', () => {
45 setTime('2024-01-01T00:00:14.997Z');
46
47 const { nextIntervalInMillis } = timer({
48 createdAt: new Date('2024-01-01T00:00:00Z'),
49 expiresAt: new Date('2024-01-01T01:00:00Z'),
50 gameIntervalInSeconds: 15,
51 });
52
53 expect(nextIntervalInMillis).toBe(3);
54 });
55
56 it('non-expiring session', () => {
57 setTime('2024-01-01T00:59:45.000Z');
58
59 const { nextIntervalAt } = timer({
60 createdAt: new Date('2024-01-01T00:00:00Z'),
61 expiresAt: new Date('2024-01-01T01:00:00Z'),
62 gameIntervalInSeconds: 15,
63 });
64
65 expect(nextIntervalAt).toBeDefined();
66 });
67
68 it('expiring session', () => {
69 setTime('2024-01-01T00:59:45.001Z');
70
71 const { nextIntervalAt } = timer({
72 createdAt: new Date('2024-01-01T00:00:00Z'),
73 expiresAt: new Date('2024-01-01T01:00:00Z'),
74 gameIntervalInSeconds: 15,
75 });
76
77 expect(nextIntervalAt).toBeUndefined();
78 });
79 });
80
81 function setTime(dt) {
82 jest.useFakeTimers().setSystemTime(new Date(dt));
83 }