Loading
Current section: Date and time 5 exercises
solution

Ticks and tasks

Loading solution

Transcript

00:00 Although working with things like frames and event loop is not technically date or time, I'm still going to use the same useFakeTimers utility from VTest because it encapsulates everything time-dependent. So I'm going to create a beforeAll hook where I'm going to call useFakeTimers the same way we did when marking the date and time or setTimeout.

00:20 And then I'm going to clean up in the afterAll hook with the useRealTimers. However, since we're working right now with microtasks, I have to specify a particular option to use fake timers. The option is called toFake, and this is the array of specific additional things for VTest to fake. Because by default, VTest will not interfere with things

00:39 like event loop, but you can make it interfere with it by providing here an argument qMicrotask. This will let VTest know that in this test, I'm about to mark something that's specific to microtasks. Now, when I did this, I can head straight to the test and basically recreate

00:55 it like we saw it before. So I'm going to create a connection event or connection instance. Then I'll create a connection listener, which is a mock function. I will add this listener, connection, addEventListener, connection as connection listener. And then now I want to

01:12 basically somehow skip to the next tick or the next frame in the event loop. What I'm going to do is call vRunAllTicks. This method is going to look up all the tasks scheduled for later, all the call frames, and run them immediately. So this way, it will be able to run this as the

01:30 first frame, and this function will allow me to run the second frame where we are dispatching the actual connection event. And once this is done, I'm able to write the assertion that the connection listener had been called once. With this, I should have my test passing

01:48 because this is precisely what's happening. By using the fake timers and configuring it to fake queue microtask, I'm able to control when and how all the frames in the event loop are being run in this test. So here I have one frame that constructs everything, my usage example, and then

02:04 I'm using vRunAllTicks in order to advance all the frames calling the dispatch event in the connection class, so then I'm able to reliably assert on the connection listener being called.