HugoDF / jest-mock-date-examples

Different approaches to mocking the Date in Jest tests

Home Page:https://codewithhugo.com/mocking-the-current-date-in-jest-tests

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

About

Different approaches to mocking the Date in Jest tests

https://codewithhugo.com/mocking-the-current-date-in-jest-tests

License:MIT License


Languages

Language:JavaScript 100.0%