In this lesson, we will set up a project using Vite and integrate Vitest as our testing framework.
Vitest is a fast and efficient test runner built on top of Vite, designed for modern JavaScript applications. It provides a seamless testing experience with features like hot module replacement (HMR) and a simple, familiar API. Vitest aims to be fast, reliable, and easy to use, making it an excellent choice for developers looking to integrate testing into their development workflow.
Creating a Vite Project
First, let’s create a new Vite project using the vanilla
template. Run the following command in your terminal:
npm create vite@latest my-test-app -- --template vanilla
Cleaning Up the Project
After creating the project, we need to clean it up a bit:
- Delete the
counter.js
andjavascript.svg
files. - Clear the contents of the
style.css
file. - Clear the contents of the
main.js
file and rename it tomain.mjs
. - Update the
index.html
file to import themain.mjs
file instead ofmain.js
:
<!-- Old -->
<!-- <script type="module" src="/main.js"></script> -->
<!-- New -->
<script type="module" src="/main.mjs"></script>
Installing Vitest
Next, we will install Vitest as a development dependency:
npm install --save-dev vitest
Adding a Test Script
To run our tests, we’ll add a test script to the package.json
file:
"scripts": {
"test": "vitest"
}
Creating a Function to Test
Create a file named math.mjs
and add a function called add
that adds two numbers:
// math.mjs
export function add(a, b) {
return a + b;
}
Writing Our First Test
Now, let’s write a test for our add
function. Create a file named math.test.mjs
:
// math.test.mjs
import { expect, test } from 'vitest';
import { add } from './math.mjs';
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
Running the Tests
Run the test script to see if our test passes:
npm run test
When the tests run successfully, you will see output indicating the tests passed:
Note: Vitest will “watch” for changes in your files and rerun the tests automatically when changes are detected.
Introducing a Bug
To see how Vitest helps in catching errors, let’s introduce a bug. Modify the add
function to subtract instead of adding:
// math.mjs
export function add(a, b) {
return a - b;
}
If you still have the test running, it will automatically rerun and show that the test fails. If not, run npm run test
again.
You will see the test failure output:
The error message will indicate the failure:
FAIL math.test.mjs > adds 1 + 2 to equal 3
AssertionError: expected -1 to be 3 // Object.is equality
This message tells us that the expected result was 3
, but our function returned -1
, showing that our function is not working as intended.
Revert the add
function to use the +
operator again, and the test will pass:
// math.mjs
export function add(a, b) {
return a + b;
}
Conclusion
Congratulations! You have successfully set up Vite with Vitest and written your first test. You also saw how Vitest helps catch errors in your code.