Skip to content

Instantly share code, notes, and snippets.

@iainnash
Created February 27, 2019 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iainnash/eb0e60cc1077173c990107b061de31ed to your computer and use it in GitHub Desktop.
Save iainnash/eb0e60cc1077173c990107b061de31ed to your computer and use it in GitHub Desktop.
// 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