茉莉花钟如何工作? [英] How jasmine clock works?

查看:137
本文介绍了茉莉花钟如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();
});

此处期望(i).toBe(1); 应该在回调中。

推荐答案

install()函数实际上用一个模拟函数替换 setTimeout ,jasmine可以让你更好地控制。这使它同步,因为没有实际等待。而是使用 tick()函数手动移动它,这也是同步的。

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.

查看源代码代码: https://github.com/jasmine/jasmine /blob/ce9600a3f63f68fb75447eb10d62fe07da83d04d/src/core/Clock.js#L21

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

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!

这篇关于茉莉花钟如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆