Migrate Tests to Vitest
Loading "Migrate Tests to Vitest"
Run locally for transcripts
Once you have the knack of how testing frameworks work, adopting one should be a walk in the park. It comes down to two steps:
- Replacing our own helper functions, like
test()
andexpect()
, with those provided by the testing framework; - Using the recommended CLI command to run the tests.
In this exercise, let's migrate to Vitest together.
π£ First, let's delete the
setup.ts
file!Gone. The purpose of that file was to implement our own tiny testing framework but since we are replacing it with Vitest now, it will provide us with the functionalities we had in
setup.ts
out of the box (like the test()
and expect()
functions).π¨ Next, install
vitest
by opening your terminal and running this command:npm install vitest --save-dev
Next, go to
tsconfig.json
and add "vitest/globals"
to the "compilerOptions.types"
key:{
"compilerOptions": {
+ "types": ["vitest/globals"]
}
}
This will tell TypeScript where to look for the type definitions for the global functions like
test()
, expect()
, and beforeAll()
.To complete the global API setup, we also need to expose the runtime implementation for those global functions.
And paste the following config in there:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
},
})
This is a basic Vitest configuration file. We are setting the
test.globals
option to true
to tell Vitest to expose functions like test()
and expect()
globally for every test.Now, all that's left is to run our existing tests using the
vitest
CLI:npx vitest
And see the result:
β greet.test.js (5)
β returns a greeting message for the given name
β returns a greeting message for the given user response
β throws on greeting user with undefined user response
β returns a congratulation message for the given name
β displays a notification when a new user joins
Test Files 1 passed (1)
Tests 5 passed (5)
Start at 17:35:57
Duration 505ms