Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you freeze / fake time with Jasmine BDD

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.

like image 222
Cezar Halmagean Avatar asked Jan 05 '12 20:01

Cezar Halmagean


People also ask

Is Jasmine TDD or BDD?

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.

Why is Jasmine tested?

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.

Is Jasmine a testing framework?

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.


2 Answers

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.

like image 70
Andreas Köberle Avatar answered Sep 28 '22 05:09

Andreas Köberle


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.

like image 33
Giles Bowkett Avatar answered Sep 28 '22 04:09

Giles Bowkett