0
0
Svelteframework~30 mins

Vitest setup in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Vitest Setup in Svelte
📖 Scenario: You are creating a new Svelte project and want to add testing using Vitest. Vitest helps you run tests easily and quickly.
🎯 Goal: Set up Vitest in a Svelte project by creating the configuration file, adding a test script, writing a simple test, and running it.
📋 What You'll Learn
Create a Vitest configuration file named vitest.config.js with Svelte support
Add a test script named test in package.json to run Vitest
Write a simple test file src/__tests__/example.test.js that checks if 2 + 2 equals 4
Run the test using the npm test command
💡 Why This Matters
🌍 Real World
Setting up Vitest is a common first step when adding automated tests to a Svelte project. It helps catch bugs early and ensures your code works as expected.
💼 Career
Many frontend developer jobs require knowledge of testing frameworks like Vitest to write reliable and maintainable code.
Progress0 / 4 steps
1
Create Vitest configuration file
Create a file named vitest.config.js in the project root. Inside it, write the code to import defineConfig from vitest/config and export the default config with test property having globals: true and environment: 'jsdom'.
Svelte
Hint

Use defineConfig from vitest/config and set globals to true and environment to 'jsdom' inside the test property.

2
Add test script to package.json
Open package.json and add a new script named test with the value vitest inside the scripts section.
Svelte
Hint

Inside package.json, find the scripts section and add "test": "vitest".

3
Write a simple test file
Create a file named src/__tests__/example.test.js. Inside it, write a test using Vitest syntax: import test and expect from vitest, then write a test named 'adds 2 + 2' that expects 2 + 2 to equal 4.
Svelte
Hint

Use test and expect from vitest. Write a test named 'adds 2 + 2' that checks if 2 + 2 equals 4.

4
Run the test
Run the test by executing the command npm test in your terminal. This will use the test script you added to package.json and run Vitest.
Svelte
Hint

Open your terminal and type npm test to run the tests using Vitest.