How jasmine clock works?

天涯浪子 提交于 2019-12-23 07:09:00

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/28889562/how-jasmine-clock-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!