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
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();
});
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With