javascript 茉莉花钟如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28889562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:42:54  来源:igfitidea点击:

How jasmine clock works?

javascriptjasminejasmine2.0ecmascript-7

提问by inf3rno

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?

我不想读几个小时的代码来找到相关的部分,但我很好奇 jasmine 是如何实现它的时钟的。它的有趣之处在于它可以使用同步测试代码来测试异步代码。AFAIK,对于当前支持 ES5 的 node.js,这是不可能的(异步函数在 ES7 中定义)。它是否使用 estraverse 之类的东西解析 js 代码并从同步测试构建异步测试?

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.

在这里,expect(i).toBe(1);应该在回调中。

回答by m59

The install()function actually replaces setTimeoutwith 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.

install()函数实际上替换setTimeout为 jasmine 为您提供更多控制权的模拟函数。这使它同步,因为没有进行实际的等待。相反,您可以手动将其与tick()函数一起向前移动,这也是同步的。

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

源码见: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 setTimeoutcall 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!

假设您有一个函数在内部将超时设置为 5 小时。Jasmine 只是替换了该setTimeout调用,以便在您调用时调用回调,tick()从而使内部计数器达到或超过 5 小时标记。这很简单!