I\'d like to change the behaviour of the standard Date object. Years between 0..99
passed to the constructor should be interpreted as fullYear
(no
Here is a solutions that is very flexible. It handles (I believe), all the different cases.
DateStub - Allows for stubbing out the Date function.
If you have
'new Date(...). ...' sprinkled throughout your code,
and you want to test it, this is for you.
It also works with 'moments'.
/**
* DateStub - Allows for stubbing out the Date function. If you have
* 'new Date(...)....' sprinkled throughout your code,
* and you want to test it, this is for you.
*
* @param {string} arguments Provide 0 to any number of dates in string format.
*
* @return a date object corresponding to the arguments passed in.
* If you pass only one date in, this will be used by all 'new Date()' calls.
* This also provides support for 'Date.UTC()', 'Date.now()', 'Date.parse()'.
* Also, this works with the moments library.
*
* Examples:
{ // Test with 1 argument
Date = DateStub('1/2/2033'); // Override 'Date'
expect(new Date().toString())
.toEqual('Sun Jan 02 2033 00:00:00 GMT-0500 (EST)');
expect(new Date().toString())
.toEqual('Sun Jan 02 2033 00:00:00 GMT-0500 (EST)');
Date = DateStub.JavaScriptDate; // Reset 'Date'
}
{ // Call subsequent arguments, each time 'new Date()' is called
Date = DateStub('1/2/1111', '1/2/1222'
, '1/2/3333', '1/2/4444'); // Override 'Date'
expect(new Date().toString())
.toEqual('Mon Jan 02 1111 00:00:00 GMT-0500 (EST)');
expect(new Date().toString())
.toEqual('Sun Jan 02 1222 00:00:00 GMT-0500 (EST)');
expect(new Date().toString())
.toEqual('Fri Jan 02 3333 00:00:00 GMT-0500 (EST)');
expect(new Date().toString())
.toEqual('Sat Jan 02 4444 00:00:00 GMT-0500 (EST)');
Date = DateStub.JavaScriptDate; // Reset 'Date'
}
{ // Test 'Date.now()'. You can also use: 'Date.UTC()', 'Date.parse()'
Date = DateStub('1/2/2033');
expect(new Date(Date.now()).toString())
.toEqual('Sun Jan 02 2033 00:00:00 GMT-0500 (EST)');
Date = DateStub.JavaScriptDate; // Reset 'Date'
}
*
* For more info: AAkcasu@gmail.com
*/
const DateStub =
function () {
function CustomDate(date) {
if (!!date) { return new DateStub.JavaScriptDate(date); }
return getNextDate();
};
function getNextDate() {
return dates[index >= length ? index - 1 : index++];
};
if (Date.name === 'Date') {
DateStub.prototype = Date.prototype;
DateStub.JavaScriptDate = Date;
// Add Date.* methods.
CustomDate.UTC = Date.UTC;
CustomDate.parse = Date.parse;
CustomDate.now = getNextDate;
}
var dateArguments = (arguments.length === 0)
? [(new DateStub.JavaScriptDate()).toString()] : arguments
, length = dateArguments.length
, index = 0
, dates = [];
for (var i = 0; i < length; i++) {
dates.push(new DateStub.JavaScriptDate(dateArguments[i]));
}
return CustomDate;
};
module.exports = DateStub;
// If you have a test file, and are using node:
// Add this to the top: const DateStub = require('./DateStub');