Spy on Date.now() results in jasmine-node not responding

2.8k Views Asked by At

I am using jasmine-node for doing unit testing. I did below code for mocking Date.now()

spyOn(Date, 'now').andReturn(1387636363717); //always return a fixed time

Then I tried to run jasmine-node spec/ but it stopped working with no output. I could not figure out what is the reason.

2

There are 2 best solutions below

2
On

I have written a tiny test. It works just fine. Using jasmin-node in version 1.11.0.

Where is your Date.now function used then?

spyOn(Date, 'now').andReturn(1387636363717);
expect(Date.now()).toEqual(1387636363717);
0
On

The problem is that there is code in node runtime (timers.js) that calls Date.now() to mark the passage of time. If you have code that sets a timer (setTimeout) and that code is executed while not using jasmine.Clock, then you may find node.js is waiting for some time to pass before executing the next real timeout. Since this code appears to be called from outside javascript land, you can not rely on the single-threaded nature of javascript to keep you safe from this. By putting a breakpoint on a .andCallFake on the Date.now spy, I was able to see that the execution of the spec was being indefinitely suspended waiting for a millisecond to pass.

This is a problem for me because we have a very large unit test suite and there are possibilities that setTimeout is called as a side effect of some other calls and jasmine.Clock is not used universally in every spec. Since this is the side effect of an optimization (note: 'too much overhead' in the comments), I would consider this to be a bug in node.js.

If you want to stop time for your tests:

  1. Spy on Date.now inside your spec function (it function - not beforeEach). That way your spec won't be delayed (also explains why @marco.jantke did not see this issue).
  2. if your code under test uses timers, use jasmine.Clock.