DEV Community

yanir manor
yanir manor

Posted on

Vite - found the missing part

Vite is a build tool that aims to provide a faster and leaner development experience for modern web projects.
The meaning of vite comes to the French word for "quick" 🇫🇷.
I love 😍 vite but something was missing 😕. how to run tests?
Yesterday vitest was open source 🍾.
Vitest is a blazing fast new unit test framework powered by Vite.
Given Jest's massive adoption, Vitest provides a compatible API that allows you to replace Jest in most projects.
Vitest includes the most common features required when setting up your unit tests (mocking, snapshots, coverage).
Vitest cares a lot about performance and uses Worker threads to run as much as possible in parallel.

Lets take vitest for a ride 🏎.

First we create new vite project

pnpm create vite

lets add vitest

pnpm i -D vitest

in src directory we will add a test file App.test.js
we will add a simple test to check its works

it('basic', () => {
Enter fullscreen mode Exit fullscreen mode

in package json we will add 2 scripts

"test": "vitest",
"coverage": "vitest --coverage"
Enter fullscreen mode Exit fullscreen mode

lets run

npm run test

and we check step one.

How can we test react component?
We can use react-test-renderer or testing-library/react.
I prefer testing-library.
For that please install

pnpm i -D @testing-library/react

and happy-dom or jsdom.
We need to rename the test file from js to jsx.
We need to edit vite.config.js and add

test: {
    environment: "happy-dom", // or 'jsdom', 'node'
Enter fullscreen mode Exit fullscreen mode

now let's create simple react component

function SimpleText () {
  return <h1>Hello World</h1>
Enter fullscreen mode Exit fullscreen mode
it('basic react with testing library', () => {
    const { getByText } = render(<SimpleText />)
    expect(getByText('Hello World')).toBeTruthy()
Enter fullscreen mode Exit fullscreen mode

That all. it's working.

In conclusion, I'm very happy about vetest.
It feels like the missing piece was found.
For more information
Home | Vite
Home | Vitest
Example | vite test via vitest
Enjoy 🥃.

Discussion (0)