Vitest's Guide to Unit Testing in JavaScript
Introduction
Section titled “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
Section titled “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
Section titled “Initial Configuration”Installation
Section titled “Installation”To get started, install Vitest in your project using npm:
npm install --save-dev vitestRunning tests
Section titled “Running 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
Section titled “Custom configuration”Vitest provides a configuration command to generate a default test configuration file:
vitest initVitest Usage
Section titled “Vitest Usage”Test Structure
Section titled “Test Structure”- The test files must be in a folder called
testlocated in the root of the project.
Main functions
Section titled “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
Section titled “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
Section titled “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.