Loading
Current section: Date and time 5 exercises
solution

Timers

Loading solution

Transcript

00:00 I will start from the test setup. Similar to mocking date, mocking timers requires me to use fake timers in vTest. So I will have to first introduce the before all hook, where I will call use fake timers, and then the after all hook, where I will call use real timers.

00:21 Now that the setup is done, I can go and see how to finish the individual tests. So here I have a mock function fn, and I debounce it by 250 milliseconds, and have a debounce function here. So first, what I want to do, I want to call the debounce function with the argument 1. And right after I call it, I want to make sure that it hasn't

00:39 been called, that debounce is actually functioning as expected. And then I want to advance the time. And for that, I will use a utility called advance timers by time in vTest. It accepts the duration in milliseconds, and here I will advance the time by 250 milliseconds. So here what's going to

00:59 happen, our physical time here in real world will not pass, but in the test, 250 milliseconds will pass. And since this is exactly the duration of this debounce window, now I will assert that this function has been called once. So I will use actually call once, and it will call with the

01:17 correct arguments. So they have been called with 1, which is the last supplied argument. This is a very straightforward use case for this debounce function, but how about the situations when it's being called repeatedly? Well, let's test those as well. So here I will

01:33 start by calling the debounce function with 1 as an argument. And right after that, I will advance the time as well, but I will advance it by a duration shorter than the debounce interval. So although this time passes, the function would still not be called. Right after this,

01:50 I will call it with the argument 2, and I will make sure that it's not been called. So I'll write assertion not to have been called. And now finally, I will advance the time by the duration

02:03 of the debounce timeout window. Now technically, what should happen is that the fn, the debounce function, should be called once, and it should be called with the correct argument, which is 2. It's the last provided argument. So let's try running these tests, and we can see that both

02:20 scenarios passing. So mocking timers is very similar to mocking date. We start with the test setup using fake timers and cleaning up with using real timers. But here in tests, we use utilities like advanced timers by time to kind of rewind the imaginary mock clock inside the test. Vetus

02:39 provides a bunch of useful utilities to work with timers and date, and I highly encourage you to explore them all in their documentation.