Last active
August 29, 2015 14:23
-
-
Save nfroidure/f12f3d798a2ef910fbc6 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
var YError = require('yerror'); | |
var _localDateCopy = global.Date; | |
var DateMock = { | |
_mocking: false, | |
_pendingQueue: [], | |
_assignedQueue: [], | |
_pendingIndex: 0, | |
start: function(theTimeQueue, options) { | |
if(DateMock._mocking) { | |
throw new YError('E_ALREADY_MOCKING'); | |
} | |
options = options || {}; | |
DateMock._pendingQueue = theTimeQueue || []; | |
DateMock._assignedQueue = []; | |
DateMock._pendingIndex = 0; | |
DateMock._mocking = true; | |
DateMock._tracing = !!options.trace; | |
return (options.global ? global : {}).Date = (function() { | |
function MockedDate() { | |
if(DateMock._tracing) { | |
console.trace(); | |
} | |
var args = []; | |
if(arguments.length) { | |
args = [].slice.call(arguments, 0); | |
} else if('undefined' === typeof DateMock._pendingQueue[DateMock._pendingIndex]) { | |
throw new YError('E_QUEUE_END', DateMock._pendingQueue, DateMock._pendingIndex); | |
} else { | |
this._index = DateMock._pendingIndex; | |
args = DateMock._pendingQueue[DateMock._pendingIndex++]; | |
if(!(args instanceof Array)) { | |
args = [args]; | |
} | |
} | |
this._assignedIndex = DateMock._assignedQueue.length; | |
DateMock._assignedQueue.push((new (_localDateCopy.bind.apply(_localDateCopy, [_localDateCopy].concat(args)))).getTime()); | |
} | |
MockedDate.now = function() { | |
return (new MockedDate()).getTime(); | |
}; | |
MockedDate.parse = function() { | |
return _localDateCopy.parse.apply(_localDateCopy, arguments); | |
}; | |
MockedDate.UTC = function() { | |
return _localDateCopy.UTC.apply(_localDateCopy, arguments); | |
}; | |
//MockedDate.prototype = {}; | |
MockedDate.prototype.constructor = _localDateCopy; | |
Object.getOwnPropertyNames(_localDateCopy.prototype).forEach(function(key) { | |
MockedDate.prototype[key] = function() { | |
var aDate = new _localDateCopy(DateMock._assignedQueue[this._assignedIndex]); | |
return (aDate)[key].apply(aDate, arguments); | |
}; | |
}); | |
return MockedDate; | |
})(); | |
}, | |
stop: function() { | |
if(!DateMock._mocking) { | |
throw new YError('E_NOT_MOCKING'); | |
} | |
DateMock.stopAnyway(); | |
if(DateMock._pendingIndex != DateMock._pendingQueue.length) { | |
throw new YError('E_QUEUE_UNCOMPLETED', DateMock._pendingIndex, DateMock._pendingQueue.length); | |
} | |
}, | |
stopAnyway: function() { | |
global.Date = _localDateCopy; | |
DateMock._mocking = false; | |
} | |
}; | |
module.exports = DateMock; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment