How do jasmine watches work?

I do not want to read the code for hours to find the corresponding part, but I am curious how jasmine fulfills its clock. Interestingly, it can test asynchronous code with a synchronization check code. AFAIK, with the current node.js that supports ES5, this is not possible (asynchronous functions are defined in ES7). Does it parse js code with something like estraverse and create an asynchronous test from synchronization?

Just an example of what I'm 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(); }); 

Here expect(i).toBe(1); must be in a callback.

+7
javascript ecmascript-7 jasmine
source share
1 answer

The install() function actually replaces setTimeout mock function that jasmine gives you more control. This makes it synchronous because the actual wait is not fulfilled. Instead, you manually move it forward using 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 have a function that internally sets a timeout of 5 hours. Jasmine simply replaces the setTimeout call so that the called call is called when tick() called, so that the internal counter reaches or exceeds the 5-hour mark. It is pretty simple!

+10
source share

All Articles