Skip to content

Instantly share code, notes, and snippets.

@anhkind
Last active August 29, 2015 14:18
Show Gist options
  • Save anhkind/746449ae78d7a9630e4f to your computer and use it in GitHub Desktop.
Save anhkind/746449ae78d7a9630e4f to your computer and use it in GitHub Desktop.
Stub JS Date
var lastNow = new Date();
var lastStubbedNow = new Date(1421224206 * 1000);
var oldDate = Date;
// stub with new Date function
Date = function () {
var args = arguments.length > 0 ? Array.prototype.slice.call(arguments) : [getStubbedNow().getTime()];
args.unshift(null)
return new ( Function.prototype.bind.apply( oldDate, args ) ) // http://stackoverflow.com/a/8843181/1036829
}
// delegate to oldDate's methods
var attributes = Object.getOwnPropertyNames(oldDate);
for (var i = 0, attr; attr = attributes[i]; i++) {
if ( oldDate.hasOwnProperty(attr) ) {
Date[attr] = (function(attr){
return oldDate[attr]
})(attr);
}
}
// stub Date.now as well
Date.now = function() {
return getStubbedNow();
}
function getStubbedNow(){
var now = new oldDate();
var offset = now - lastNow;
return new oldDate(lastStubbedNow.getTime() + offset);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment