ENWritten in English7 min read
Mastering Time-Related Unit Tests with “vitest”
Why time-related features are hard to test, and how Vitest's fake timers make those tests fast and predictable.

Vitest is a powerful tool to create tests to time-related feature.
Unit testing plays a crucial role in software development, guaranteeing the reliability and strength of our code. Yet, when it comes to testing time-related features, specific challenges arise. By mastering the implementation of unit tests for time-related features, we can overcome these obstacles and gain greater confidence in our code.
Join me as we explore the realm of time-related unit tests and uncover their potential to transform the way we build precise and dependable applications.
The Importance of Unit Testing and Its Preventative Power
I personally like the way Sten Pittet described Unit tests in Atlassian's blog (opens in a new tab):
Unit tests are very low level and close to the source of an application. They consist in testing individual methods and functions of the classes, components, or modules used by your software. Unit tests are generally quite cheap to automate and can run very quickly by a continuous integration server.
By writing tests for individual code units, we can catch bugs early, saving time and effort. Unit tests act as a safety net during code changes, providing reassurance that desired functionality remains intact. They help us refactor with confidence and maintain stable software.
Understanding the Challenges of Testing Time-Related Features
When it comes to testing time-related features in software development, we encounter unique challenges that require careful consideration. These challenges stem from the nature of time itself and the dependencies our code has on it. Let's explore some of these challenges and understand why testing time-related features can be complex:
- Non-Deterministic Results: Time-related features often introduce non-determinism in our code. That means, the behavior of our code can vary based on the current time, making it difficult to predict and reproduce specific scenarios during testing.
- Real-Time Dependencies: Testing time-related features requires dealing with real-time dependencies, such as waiting for intervals or timeouts. Relying on actual time during testing can slow down the testing process and introduce inconsistencies.
- Timing Inaccuracies: Time-related features may rely on precise timing intervals. However, factors like system load or processing delays can cause timing inaccuracies, making it challenging to assert the expected behavior accurately.
Testing time-related features can be complex due to the non-deterministic nature of time and the real-time dependencies that our code relies on.
By addressing these challenges head-on and implementing appropriate testing techniques, we can ensure the reliability and accuracy of our time-dependent code.
Let's get to it already!
Before diving into the practical aspects of unit testing, let's take a moment to familiarize ourselves with a few essential concepts that form the foundation of effective testing.
- Testing Frameworks: Testing frameworks provide a set of tools and conventions for organizing and executing tests. They offer functionalities such as assertions, test case management, and test result reporting.
- Test Runners: Test runners are tools or libraries that automate the execution of our unit tests. They scan our codebase for test files, run the tests, and provide us with feedback on the test results. Test runners help streamline the testing process by executing tests in an efficient manner, handling setup and teardown operations, and generating comprehensive reports that assist in identifying failures and errors.
- Mock Objects: Mock objects are simulated versions of dependencies or external components that we use during testing. They mimic the behavior of real objects, allowing us to isolate specific units of code and verify their interactions. By utilizing mock objects, we can control and manipulate the behavior of dependencies, making our tests more focused, predictable, and independent.
- Fake Timers: Fake timers are powerful tools that allow us to simulate the passage of time in controlled environments. By mocking the behavior of real timers, we gain control over time-related features during testing.
In this tutorial we will use the Vitest (opens in a new tab) framework. It is a very fast testing framework native to Vite (opens in a new tab), so you will need to install these two dependencies:
yarn add -D vite vitestThen, we will need to create a folder to house all our tests. This folder will serve as a centralized location where we can organize and manage our test files effectively. Let's create a folder named "tests" at the root level of our project directory. By maintaining a separate folder for tests, we can easily locate and run our tests whenever needed, ensuring a structured and efficient testing workflow.
Inside that folder, we will create setup.ts to configure how vitest will work with the tests we'll write:
// setup.ts
import { afterEach, beforeEach, vi } from 'vitest';
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});With this setup, we tell vitest to use the fake timers before we run a test case, then after the case run, back to use real timers.
After that, we can create a .test.ts file for each test suite that our application have. In this example, I'm using my timer hook as the use case. So I'll create a single useTimer.test.ts.
// useTimer.test.ts
test('should decrease current time at specified interval', () => {
const { result } = renderHook(() => useTimer(5, { interval: 200 }));
result.current.start();
expect(result.current.currentTime).toBe(5);
vi.advanceTimersByTime(100);
expect(result.current.currentTime).toBe(5);
vi.advanceTimersByTime(100);
expect(result.current.currentTime).toBe(4);
});Let's understand each part of the code
- The
test()method specifies that we are creating a test case. In the example above, we create a case to test that the timer should decrease the "current time" variable at specified interval, 200ms. Its first parameter is the case's name. The second parameter is the test function that holds the expectations to the case. - In the first line of that function, I create an instance of the hook
useTimer(opens in a new tab), which creates a 5-seconds timer with an interval of 200 ms between each timer tick. For now I'm not gonna get deep in this implementation, but it should work just fine if you are using a regular function instead of a React Hook. If you would like to know more about this hook, please check my post about it. - Then, the timer is started by calling its method
start(). - The next line comes with the very first assertion of our test case, it uses
expectfunction to do so. Here the code is expecting the timer's current time to be 5 (the initial value that we specified in the first line). - Vitest provides utility functions to help you out through its
vihelper (opens in a new tab). The method that we are using isadvanceTimersByTime(100). With this method, we can "advance" the fake timer by 100 ms. - After 100 ms, the timer's current time should still be 5, as the interval between each tick is 200 ms. We can assert this with the
expectfunction expecting the current time variable to still be 5. - Advancing the fake timer by more 100 ms calling
vi.advanceTimersByTime(100)again. Now the fake timer has advanced 200 ms since we started the test case run. - After 200 ms, the timer should have decreased. To assert that, we use
expectfunction again, but now we will expect the current time to be 4.
By understanding and utilizing these test elements, such as declaring test cases, making assertions with the expect function, and leveraging the vi helper provided by Vitest, we can effectively write and validate our unit tests for time-related features.

Conclusion
Mastering unit testing requires practice, patience, and a commitment to writing thorough tests. With each test we create, we strengthen our codebase, enhance maintainability, and build confidence in the reliability of our software.
So, embrace the power of unit testing and the use of tools like Vitest to level up your testing game. Start implementing comprehensive tests for your time-related features and witness the benefits firsthand. Your future self and your development team will thank you for it.
Happy testing!
Further reading…
That's all! Hope you enjoyed that article! Here are some other link to check and improve your knowledge:
- The official site to Vitest documentation: Vitest | A blazing fast unit test framework powered by Vite (opens in a new tab)
- How to Write Good Unit Tests: 14 Tips (leanylabs.com) (opens in a new tab)
- 6 Best Practices to Get Up To Speed (stackify.com) (opens in a new tab)
- Creating Timers in React: Simplifying Time Management With Hooks
Originally published on Medium (opens in a new tab).