Vitest for TypeScript
Vitest is a fast and modern testing framework that integrates seamlessly with Vite-based projects. It offers excellent TypeScript support, making it a great choice for developers looking to leverage cutting-edge tools in their workflow. This guide will walk you through configuring Vitest for your TypeScript project.
Prerequisites
Before configuring Vitest, ensure you have the following:
-
Vite Installed: If your project is not already using Vite, set it up by running:
npm create vite@latest my-project cd my-project npm install -
TypeScript: Ensure your project is set up for TypeScript:
npm install typescript --save-dev npx tsc --init -
Vitest: Install Vitest and its TypeScript-related dependencies:
npm install vitest ts-node --save-dev -
Node.js: Ensure you have Node.js installed. Download the latest version from Node.js.
Configuration Steps
-
Update vite.config.ts
Vitest integrates with Vite through its configuration file. Open or create vite.config.ts and add the following configuration:
import { defineConfig } from 'vite'; import { resolve } from 'path'; import { configDefaults } from 'vitest/config'; export default defineConfig({ resolve: { alias: { '@': resolve(__dirname, './src'), }, }, test: { globals: true, environment: 'node', exclude: [...configDefaults.exclude, '**/dist/**'], coverage: { provider: 'istanbul', reporter: ['text', 'html'], }, }, });
-
Verify TypeScript Configuration
Ensure your tsconfig.json includes options compatible with Vitest. Here’s an example:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "Node", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "jsx": "react-jsx", "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*.ts"], "exclude": ["node_modules", "**/*.test.ts"] }
-
Add Test Scripts
Update your package.json to include test scripts:
"scripts": { "test": "vitest", "test:watch": "vitest --watch", }
-
Write a Test
Create a test file in your project, for example, src/sample.test.ts:
function sum(a: number, b: number): number { return a + b; } test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
-
Run Tests
Run your tests using the following script:
npm test
With this setup, your TypeScript project is ready to leverage Vitest for robust and efficient unit testing. Happy testing!