Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jasmine spyOn on javascript new Date

I am unit testing the my client code in angulajs and i understand this code means

 var newdate = new Date(2013,6,29);
    spyOn(Date.prototype, 'getTime').and.callFake(function() {
          return newdate;
        });

we mockout the getTime() methode of the Date object. but i want to mock out the new Date() instead. for example the code i want to test contains this line

payload.created_at = new Date();

I dont have access to payload.created_at. so i want to tell jasmine that whenever you see new Date(), replace that with a given date i give you. So i was thinking of something like but it doesnt work.

spyOn(Date.prototype, 'new Date').and.callFake(function() {
          return newdate;
        });

but new Date is not a method of the Date. Please can someone help me figure this out? thanks

like image 914
user3137376 Avatar asked Jun 02 '15 17:06

user3137376


2 Answers

The Jasmine Clock api allows you to fake out the JavaScript Date functionality without manually writing a spy for it.

In particular, read the section about mocking the date.

describe("Mocking the Date object", function(){
    beforeEach(function() {
      jasmine.clock().install();
    });

    it("mocks the Date object and sets it to a given time", function() {
      var baseTime = new Date(2013, 9, 23);

      jasmine.clock().mockDate(baseTime);

      jasmine.clock().tick(50);
      expect(new Date().getTime()).toEqual(baseTime.getTime() + 50);
    });

    afterEach(function() {
      jasmine.clock().uninstall();
    });
});
like image 176
johnmcase Avatar answered Nov 07 '22 06:11

johnmcase


so this link [Mock date constructor with Jasmine had the answer but it wasn't working for me for some reason. I guess it might i have to do with my jasmine version but below is the code that worked for me

var oldDate = new Date();
    spyOn(window, 'Date').and.callFake(function() {
      return oldDate;
    });

there is a difference in the .and.callFake of the code above and that in the link above. Thanks

like image 36
user3137376 Avatar answered Nov 07 '22 06:11

user3137376