Created
November 17, 2011 21:16
-
-
Save searls/1374556 to your computer and use it in GitHub Desktop.
Faking dates in jasmine
This file contains hidden or 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
/* Faking dates | |
* when I need to fake a date, my preferred way is to introduce a new | |
* production method that returns the date I need (usually I need the | |
* current date, but it could just as well forward arguments). Once | |
* we have it, we can spy on it just like we could anything else. | |
* **/ | |
window.currentDate = function() { return new Date(); }; | |
window.newAllyMcbealTonight = function(){ | |
return currentDate().getFullYear() == 1998; | |
}; |
This file contains hidden or 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
describe(".currentDate", function() { | |
it("returns the current date", function() { | |
expect(window.currentDate()).toBeWithinASecondOf(new Date()); | |
}); | |
}); | |
describe("the 90s",function(){ | |
beforeEach(function(){ | |
fakeDate(1998,11,10); | |
}); | |
it("has a new ally mcbeal tonight!",function(){ | |
expect(newAllyMcbealTonight()).toBe(true); | |
}); | |
}); | |
var fakeDate = function(year,month,day) { | |
spyOn(window, "currentDate").andCallFake(function() { return new Date(year,month,day); }); | |
}; | |
beforeEach(function(){ | |
this.addMatchers({ | |
toBeWithinASecondOf: function(date) { | |
return Math.abs(this.actual.getTime() - date.getTime()) < 1000; | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment