javascript - Mock only today's date in Jasmine unit test -


i writing jasmine unit test function in dates compared. want provide fake date used today's date. therefore spying on date method on window object , returning predefined date.

this works fine, in function i'm testing, reading dates string , calling new date(yyyy, mm, dd) turn them dates. when occurs, these values replaced mock date provided.

here's example:

var checkdate = function () {             return { today: new date(), anotherday: new date(2016, 0, 1) }         };  var createdate = function (year, month, date) {   var overridedate = new date(year, month, date);   spyon(window, 'date').andcallfake(function () {     return overridedate;   }) }  var dates;  describe("checkdate", function() {   beforeeach(function() {     createdate(2015, 11, 1);     dates = checkdate();   })   it("today has value of 12/1/2015", function() {     expect(dates.today.tolocaledatestring()).tobe('12/1/2015');   });   it("anotherday has value of 1/1/2016", function() {     expect(dates.anotherday.tolocaledatestring()).tobe('1/1/2016');   }) }); 

here's jsfiddle example of issue.

how can mock today's date, , allow new date(yyyy, mm, dd) create proper date object? expect both tests in fiddle pass, i.e. anotherday set 1/1/2016 , today set 12/1/2015.

karma-jasmine v 0.1.6.

you can cache window.date use when arguments passed mock

var windowdate = window.date; spyon(window, 'date').andcallfake(function (year,month,day) {     if(year != undefined && month != undefined && day != undefined){         return new windowdate(year,month,day);         }   return overridedate; }) 

https://jsfiddle.net/n3lf0g8p/1/


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -