15

I don't want to read code for hours to find the relevant part, but I am curious how jasmine implements its clock. The interesting thing with it is that it can test async code with sync testing code. AFAIK, with the current node.js, which supports ES5, this is not possible (async functions are defined in ES7). Does it parse the js code with something like estraverse and build an async test from the sync one?

Just an example of what I am talking about:

it("can test async code with sync testing code", function () {
    jasmine.clock().install();

    var i = 0;
    var asyncIncrease = function () {
        setTimeout(function () {
            ++i;
        }, 1);
    };

    expect(i).toBe(0);
    asyncIncrease();
    expect(i).toBe(0);
    jasmine.clock().tick(2);
    expect(i).toBe(1);

    jasmine.clock().uninstall();
});

In here the expect(i).toBe(1); should be in a callback.

76484
  • 8,498
  • 3
  • 19
  • 30
inf3rno
  • 24,976
  • 11
  • 115
  • 197

1 Answers1

18

The install() function actually replaces setTimeout with a mock function that jasmine gives you more control over. This makes it synchronous, because no actual waiting is done. Instead, you manually move it forward with the tick() function, which is also synchronous.

See the source code: https://github.com/jasmine/jasmine/blob/ce9600a3f63f68fb75447eb10d62fe07da83d04d/src/core/Clock.js#L21

Suppose you had a function that internally set a timeout of 5 hours. Jasmine just replaces that setTimeout call so that the callback will be called when you call tick() so that the internal counter reaches or exceeds the 5 hour mark. It's quite simple!

m59
  • 43,214
  • 14
  • 119
  • 136
  • So this won't work by real async code, e.g. by db connection? – inf3rno Mar 05 '15 at 23:20
  • 2
    @inf3rno For ajax stuff, you'd either want to mock the ajax call (assume the server works) or for integration tests, actually let it be async. – m59 Mar 05 '15 at 23:23
  • Ok. I'm working on an async framework for ES5, that's why I asked. Thanks! :-) – inf3rno Mar 05 '15 at 23:26
  • So all the timeouts that are set while the Jasmine clock is installed, will be removed when the clock is uninstalled? They will not start running again after you uninstall it? – user2602152 Jan 14 '16 at 09:12
  • 1
    http://jasmine.github.io/2.0/introduction.html#section-Mocking_the_JavaScript_Timeout_Functions – apple16 May 07 '16 at 18:14
  • Actually is not "quite simple". What a hack! Thanks for the explanation :) You made it at least "simpler" ;) – Alfonso Nishikawa May 31 '16 at 08:18