I have a line like this in my code
new Date().getFullYear();
and I need it to always return the same year.
Is there any way to do this with Jasmine ?
Thanks.
The current home page of Jasmine says that it's “a behavior-driven development framework for testing JavaScript code.” So the intent of Jasmine is to be a BDD testing framework, per its authors. So, while the authors of Jasmine have intended it as a BDD testing framework, it can also be used with TDD and unit testing.
Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.
Jasmine is a framework for unit testing JavaScript. It's open source and has more than 15,000 stars on GitHub at the time of this writing. Its popularity among developers means that it has a strong community and documentation available when you get stuck.
In JavaScript you can simply overwrite the function in your test setup:
Date.prototype.getFullYear = function(){return 2012}
You could also use a jasmine spy:
spyOn(Date, 'getFullYear').andReturn(2012)
Another way is to insert the date into your function you wanna test. Which is btw. the best way to write testable code. Dont create new instances in your functions, cause you always start to test not only your code but also this instances.
Sinon.js fake timers.
http://sinonjs.org/docs/#clock
I built a drum machine in Node.js using this in my specs to check the timing code. but I also worked with it on another project where the only way I could get it to be the year I wanted was by using one specific year, I think 1969 for some reason. I'm guessing that's the start of the Unix era.
anyway, that was almost a year ago, so they've probably fixed it by now.
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