茉莉花钟的工作原理是什么?

How jasmine clock works?(茉莉花钟的工作原理是什么?)
本文介绍了茉莉花钟的工作原理是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我不想花几个小时阅读代码来找到相关部分,但我很好奇 jasmine 如何实现它的时钟.它的有趣之处在于它可以使用同步测试代码来测试异步代码.AFAIK,使用当前支持 ES5 的 node.js,这是不可能的(异步函数在 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();
});

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

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

推荐答案

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!

这篇关于茉莉花钟的工作原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)