Vitest's Guide to Unit Testing in JavaScript
Introduction
Vitest is a unit testing framework for JavaScript, designed specifically to work with Vite. It uses Vite as a package to provide an improved development experience and consistent configuration between your application and tests. Vitest is compatible with the Jest API, making it easy to migrate from Jest in various build configurations.
Official documentation: Vitest
Key features of Vitest
- Reuse Vite configuration, transformers, resolvers and plugins.
- Jest-compatible APIs for easy migration from Jest.
- Out-of-the-box ESM, TypeScript and JSX support.
- Improved performance with fast builds thanks to esbuild.
Initial Configuration
Installation
To get started, install Vitest in your project using npm:
npm install --save-dev vitestRunning tests
- To integrate it into your
package.json, you can add a test script:
{ "scripts": { "test": "vitest" }}- After installing Vitest, you can run your tests with the
vitestcommand:
npm run vitestCustom configuration
Vitest provides a configuration command to generate a default test configuration file:
vitest initVitest Usage
Test Structure
- The test files must be in a folder called
testlocated in the root of the project.
Main functions
In Vitest, we mainly use two functions to write tests: describe and it.
- describe**: Used to group related tests together. It takes a string to describe what is being tested and a callback function that contains the tests.
- is used to define individual tests. Similar to describe, it takes a string for the description and a callback function for the test logic.
Example Usage
Here is an example of how to use describe and it in a Vitest test suite for a login functionality:
import { describe, it, expect } from "vitest";import AWS from "aws-sdk";
const dynamodb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });
describe("Login functionality", () => { it("should authenticate a valid user", async () => { // Insert a test user into DynamoDB // ... // Perform login with valid credentials // ... // Expectations });
it("should reject an invalid user", async () => { // Perform login with invalid credentials // ... // Expectations });});Conclusion
- Vitest offers an improved testing experience and seamless integration with Vite. Its support for the Jest API makes it easy to migrate from Jest, and its focus on performance ensures fast and efficient test runs.