Created
February 27, 2019 21:36
-
-
Save iainnash/eb0e60cc1077173c990107b061de31ed to your computer and use it in GitHub Desktop.
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
// Mocking out the Date.now() function (not used by moment) | |
const realDateNow = Date.now; | |
jest.spyOn(Date, 'now').mockImplementation(() => new Date('2019-01-01')); | |
// Test code here | |
Date.now.mockRestore(); | |
// Mocking out Date constructor object (used by moment) | |
const nowString = '2018-02-02T20:20:20'; | |
// Mock out the date object to return a mock null constructor | |
const MockDate = (lastDate) => (...args) => | |
new lastDate(...(args.length ? args : [nowString]); | |
global.Date = jest.fn(MockDate(global.Date)); | |
// Test code here | |
global.Date.mockRestore(); | |
// Using mockdate library | |
import MockDate from 'mockdate'; | |
MockDate.set('2018-1-1'); | |
// Test code here | |
MockDate.reset(); | |
// Using sinon library | |
import sinon from 'sinon'; | |
// Mocking with Sinon (also mocks timers) | |
const clock = sinon.useFakeTimers(new Date('2018-01-01')); | |
// Restoring | |
clock.restore(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment