Skip to content
Different approaches to mocking the Date in Jest tests
Branch: master
Clone or download
Latest commit 7bdc401 Jun 20, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src run lint --fix Jun 19, 2019
.editorconfig initial commit Jun 19, 2019
.gitignore initial commit Jun 19, 2019
LICENSE initial commit Jun 19, 2019
README.md add setup instructions Jun 19, 2019
package.json run lint --fix Jun 19, 2019
yarn.lock initial commit Jun 19, 2019

README.md

Jest Mock Date examples

Different approaches to mocking the Date in Jest tests

See the full post and explanation at codewithhugo.com/mocking-the-current-date-in-jest-tests.

There are 2 general approaches to mocking the current date:

  • Using new Date() and mocking the constructor.
  • Using new Date(Date.now()) and mocking the output of Date.now().

For each of those approaches in the application code, this repo has examples for a spy-based approach and a full function/constructor stub/mock replacement:

Running the tests

Packages were installed with yarn, although npm should work just as well.

  • Run yarn
  • Run yarn test
You can’t perform that action at this time.