Created
November 8, 2019 10:17
-
-
Save loilo/de97735f0860f0f1b8f86b3601a5cabf to your computer and use it in GitHub Desktop.
Jest: Mock datetime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Fixates JavaScript's Date | |
* This is useful for snapshot testing data which refers to the current time | |
* | |
* Losely based on https://github.com/facebook/jest/issues/2234#issuecomment-324868057 | |
*/ | |
/** | |
* Keep a reference to the original date | |
*/ | |
const OriginalDate = Date | |
/** | |
* Globally fixate the JavaScript datetime | |
* | |
* @param {...any} fixedDateArgs The fixed arguments passed to the Date constructor | |
* | |
* @example | |
* fixate(2019, 0, 1) // Fixate date to January 1, 2019, 00:00:00.000 of local time | |
* fixate('2015-08-15T14:30:00+02:00') // Fixate date to August 15, 2015, 14:30:00.000 of CEST | |
*/ | |
function fixate(...fixedDateArgs) { | |
// eslint-disable-next-line no-global-assign | |
Date = class extends OriginalDate { | |
constructor() { | |
return new OriginalDate(...fixedDateArgs) | |
} | |
} | |
Date.now = () => new Date().getTime() | |
} | |
/** | |
* Release the previously fixated datetime | |
* You probably want to call this in afterEach() | |
* | |
* @example | |
* release() | |
*/ | |
function release() { | |
// eslint-disable-next-line no-global-assign | |
Date = OriginalDate | |
} | |
module.exports = { fixate, release } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment