Skip to content

Instantly share code, notes, and snippets.

@vnegrisolo
Created June 20, 2016 20:02
Show Gist options
  • Save vnegrisolo/fa9bbdae2df3778a1bfd54c3b10d3458 to your computer and use it in GitHub Desktop.
Save vnegrisolo/fa9bbdae2df3778a1bfd54c3b10d3458 to your computer and use it in GitHub Desktop.
Time travel feature to be used in tests. This overrides `new Date()` to use the specified date, otherwise will call the original implementation.
// usage:
// import { travelTo, travelToPresent } from '../helpers/time-traveling';
//
// beforeEach() { travelTo(2016, 6, 10); },
// afterEach() { travelToPresent(); }
//
const DateOriginal = Date;
export function travelToPresent() {
window.Date = DateOriginal;
}
export function travelTo(year, month, day, hour, minute, seconds) {
const TimeTravelingDate = function f() {
if(this instanceof f) {
if(arguments.length <= 0) {
return new DateOriginal(
year || 2000,
month - 1 || 0,
day || 1,
hour || 0,
minute || 0,
seconds || 0
);
} else {
let args = [].slice.call(arguments);
args.unshift(window);
return new (Function.prototype.bind.apply(DateOriginal, args))();
}
} else {
return DateOriginal.apply(window, arguments);
}
};
TimeTravelingDate.parse = DateOriginal.parse;
TimeTravelingDate.UTC = DateOriginal.UTC;
TimeTravelingDate.prototype = DateOriginal.prototype;
window.Date = TimeTravelingDate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment