Skip to content

Instantly share code, notes, and snippets.

@searls
Created November 17, 2011 21:16
Show Gist options
  • Save searls/1374556 to your computer and use it in GitHub Desktop.
Save searls/1374556 to your computer and use it in GitHub Desktop.
Faking dates in jasmine
/* 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;
};
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