Unit testing is one of the easiest ways to make your JavaScript code more reliable. A unit test checks a small piece of code in isolation and confirms that it behaves as expected.
In this article, we will set up a very simple testing stack using Vitest then write our first unit tests for a basic application.
Why Unit Testing?
When building a website, even a simple one, you usually have small pieces of logic:
- calculating totals
- validating form input
- changing text on the page
- reacting to button clicks
- updating HTML elements
Unit tests help you make sure these small pieces continue to work when you change your code later.
The tech stack
For this setup, we will use:
- Vitest: a fast JavaScript testing framework
- jsdom: a browser-like DOM environment for Node.js
Vitest runs our tests. jsdom gives us access to browser-like objects such as document, window, and HTML elements while running tests outside a real browser.
Installing packages
First, install the dependencies:
npm install -D vitest jsdom
Then update your packages.json

Now you can run your test with
npm test
Testing a function
Let’s start with a pure JavaScript function. A pure function is easy to test because it does not depend on the browser, HTML, or external state.
Create a file called cart.js

Now create a test file called cart.spec.js

This test checks that when the price is 50 and the quantity is 3, the total is 150.
Run the test
npm test
Everything works and Vitest shows the test results

