Requirements
- Node.js installed with v18 or higher
- Basic Node.js app
What is Vitest?
Vitest is a fast and simple testing framework for Node.js, React, Next.js, Vue, Svelte, etc. It's built on top of Vite, which is a fast build tool for JavaScript and TypeScript. Vitest is also compatible with Jest, which is another popular testing framework.
Installation
Firstly, we will install Vitest as a development dependency:
Configuring the project
To run tests with Vitest, we need to add a script to our package.json
. We will call it test
:
Adding a test file
Now that we have added the test script, we can start adding test files. Vitest will by default search for files ending with .test.js
or .test.ts
.
Let's create a file called math.test.ts
in the src
folder:
If you're not familiar with the test
and expect
functions, they allow use write assertions and tests. In simple terms:
test
: Run a test with a name and a function.expect
: Make sure that the value is equal to the expected value.
Running the tests
To run these tests, simply run the test
command we created earlier:
This will show all passed and failed tests.
Tip: You can also view the test results in the browser by adding the --ui
flag to the test
command:
More from Vitest
You can use Vitest for many more project types, such as: React, Next.js, Vue, Svelte, etc. Read more about the awesomeness Vitest can do on their documentation
Personally, I use Vitest in many of my projects and I absolutely love it! It's simple to set up, fast and has a great community.