0
# Jest Date Mock
1
2
Jest Date Mock is a Jest testing utility that enables developers to mock the Date class for consistent and predictable unit tests. It provides simple controls to advance, set, or reset mocked time, supporting both browser and Node.js environments with automatic environment detection.
3
4
## Package Information
5
6
- **Package Name**: jest-date-mock
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install --save-dev jest-date-mock`
10
11
## Core Imports
12
13
```javascript
14
import { advanceBy, advanceTo, clear } from "jest-date-mock";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { advanceBy, advanceTo, clear } = require("jest-date-mock");
21
```
22
23
## Basic Usage
24
25
```javascript
26
import { advanceBy, advanceTo, clear } from "jest-date-mock";
27
28
describe("Date mocking tests", () => {
29
beforeEach(() => {
30
// Set a fixed date for consistent testing
31
advanceTo(new Date("2023-01-01T00:00:00.000Z"));
32
});
33
34
afterEach(() => {
35
// Reset to real time after each test
36
clear();
37
});
38
39
test("should mock Date constructor", () => {
40
const now = new Date();
41
expect(now.toISOString()).toBe("2023-01-01T00:00:00.000Z");
42
});
43
44
test("should advance time", () => {
45
advanceBy(1000); // Advance by 1 second
46
const now = new Date();
47
expect(now.toISOString()).toBe("2023-01-01T00:00:01.000Z");
48
});
49
});
50
```
51
52
## Architecture
53
54
Jest Date Mock uses a sophisticated approach to provide seamless Date mocking across different JavaScript environments:
55
56
**Environment Detection**: The package automatically detects the runtime environment on import and applies the appropriate mocking strategy:
57
- **Node.js environment**: Replaces `global.Date` with the mocked implementation
58
- **Browser environment**: Replaces `global.window.Date` with the mocked implementation
59
60
**Date Class Replacement**: The core mocking mechanism creates a new Date class that inherits from the original Date class while intercepting constructor calls and static methods. This ensures full API compatibility while enabling time control.
61
62
**State Management**: Internal state tracks the current mocked timestamp, with three states:
63
- **Unmocked** (undefined): Uses real system time
64
- **Fixed time**: Returns the set timestamp
65
- **Advanced time**: Calculates time based on initial timestamp plus accumulated advances
66
67
**Prototype Chain Preservation**: The mocked Date class maintains the complete prototype chain and constructor relationships, ensuring instanceof checks and method availability work correctly.
68
69
## Jest Configuration
70
71
Add to your `package.json`:
72
73
```json
74
{
75
"jest": {
76
"setupFiles": ["jest-date-mock"]
77
}
78
}
79
```
80
81
Or if you already have setupFiles:
82
83
```json
84
{
85
"jest": {
86
"setupFiles": ["./__setups__/other.js", "jest-date-mock"]
87
}
88
}
89
```
90
91
## Capabilities
92
93
### Advance Time by Offset
94
95
Advances the current mocked date by specified milliseconds.
96
97
```javascript { .api }
98
/**
99
* Advances the current mocked date by specified milliseconds
100
* @param {number} ms - Milliseconds to advance the date by (defaults to 0 if falsy)
101
* @returns {number} The new timestamp after advancing
102
*/
103
function advanceBy(ms?: number): number;
104
```
105
106
**Usage:**
107
108
```javascript
109
import { advanceBy } from "jest-date-mock";
110
111
// Start from current time if no mock is active
112
advanceBy(5000); // Advance by 5 seconds
113
114
// Or advance from existing mock time
115
advanceTo(new Date("2023-01-01T00:00:00.000Z"));
116
advanceBy(60000); // Now at 2023-01-01T00:01:00.000Z
117
```
118
119
### Set Specific Time
120
121
Sets the mocked date to a specific timestamp.
122
123
```javascript { .api }
124
/**
125
* Sets the mocked date to a specific timestamp
126
* @param {number|Date|string} ms - Timestamp, Date object, or date string to set mock to; if falsy, sets to epoch (0)
127
* @returns {number} The timestamp that was set
128
*/
129
function advanceTo(ms?: number | Date | string): number;
130
```
131
132
**Usage:**
133
134
```javascript
135
import { advanceTo } from "jest-date-mock";
136
137
// Set to specific date
138
advanceTo(new Date("2023-06-15T12:30:00.000Z"));
139
140
// Set to timestamp
141
advanceTo(1687094200000);
142
143
// Set to epoch (if falsy value provided)
144
advanceTo(0);
145
advanceTo(null);
146
advanceTo(undefined);
147
```
148
149
### Clear Date Mock
150
151
Clears the date mock, returning to real-time Date behavior.
152
153
```javascript { .api }
154
/**
155
* Clears the date mock, returning to real-time Date behavior
156
* @returns {undefined}
157
*/
158
function clear(): undefined;
159
```
160
161
**Usage:**
162
163
```javascript
164
import { clear } from "jest-date-mock";
165
166
// After setting up mocks
167
advanceTo(new Date("2023-01-01"));
168
169
// Clear the mock to return to real time
170
clear();
171
172
// Now Date will return actual current time
173
const realNow = new Date();
174
```
175
176
### Version
177
178
Package version string constant.
179
180
```javascript { .api }
181
const version: string;
182
```
183
184
## Types
185
186
```javascript { .api }
187
/**
188
* The Date constructor interface
189
*/
190
interface DateConstructor {
191
new (): Date;
192
new (value: number | string): Date;
193
new (year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date;
194
(): string;
195
readonly prototype: Date;
196
now(): number;
197
parse(s: string): number;
198
UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;
199
}
200
```
201
202
## Environment Support
203
204
jest-date-mock automatically detects the runtime environment and applies the appropriate mocking:
205
206
- **Node.js environment**: Mocks `global.Date`
207
- **Browser environment**: Mocks `global.window.Date`
208
209
The package works seamlessly in both environments without any additional configuration.
210
211
## Mocked Date Class Features
212
213
When active, the mocked Date class provides:
214
215
- **Full Date API compatibility**: All standard Date methods and properties work normally
216
- **Constructor mocking**: `new Date()` returns the mocked time
217
- **Static method mocking**: `Date.now()` returns the mocked timestamp
218
- **Original Date access**: `Date.__OriginalDate__` provides access to the original Date class
219
- **Real-time access**: `Date.current()` returns the actual current time regardless of mock state
220
221
## Enhanced Date Class API
222
223
When jest-date-mock is active, the global Date class is enhanced with additional methods:
224
225
```javascript { .api }
226
/**
227
* Returns the mocked timestamp, or real time if no mock is active
228
* @returns {number} Current timestamp in milliseconds
229
*/
230
Date.now(): number;
231
232
/**
233
* Reference to the original, unmocked Date class
234
* @type {DateConstructor}
235
*/
236
Date.__OriginalDate__: DateConstructor;
237
238
/**
239
* Returns the actual current system time, ignoring any active mock
240
* @returns {number} Real system timestamp in milliseconds
241
*/
242
Date.current(): number;
243
```
244
245
## Testing Patterns
246
247
### Setup and Teardown
248
249
```javascript
250
import { advanceTo, clear } from "jest-date-mock";
251
252
describe("Time-dependent functionality", () => {
253
beforeEach(() => {
254
// Set consistent starting point
255
advanceTo(new Date("2023-01-01T00:00:00.000Z"));
256
});
257
258
afterEach(() => {
259
// Clean up after each test
260
clear();
261
});
262
263
// Your tests here
264
});
265
```
266
267
### Testing Time Progression
268
269
```javascript
270
import { advanceBy, advanceTo } from "jest-date-mock";
271
272
test("should handle time progression", () => {
273
advanceTo(new Date("2023-01-01T00:00:00.000Z"));
274
275
const start = new Date();
276
advanceBy(60000); // Advance 1 minute
277
const end = new Date();
278
279
expect(end.getTime() - start.getTime()).toBe(60000);
280
});
281
```