Next.js - Testing With Vitest



In this chapter, we will explore Vitest testing framework, how to setup Vitest in Next.js application and how to write tests for Next.js components, hooks, and functions.

What is Vitest?

Vitest is a modern testing framework built on top of Vite, the JavaScript framework. It supports multiple types of testing needs such as unit tests, integration tests, and end-to-end tests. Vitest is known for it's integration with Vite framework ensuring fast and optimized builds. Just like other frameworks, Vitest offers features like snapshot testing, code coverage reporting, and watch mode for real-time feedback.

Create a Next.js application with Vitest

In Next.js, you can create a new project with Vitest and React Testing Library already configured. To create a new Next.js project with Vitest, run the following command:

npx create-next-app@latest --example with-jest with-jest-app

This will create a new Next.js project with Vitest and React Testing Library already configured. The project will include pre-configured vitest.config.ts, vitest.setup.ts, example test files, and all necessary dependencies.

Setting Up Vitest in a Next.js Application

Setting up Vitest in Next.js include manually installing and configuring Vitest, then defining dependencies and devDependencies in the project folder. The following section shows how to set up Vitest in a Next.js application.

Step 1. Install Vitest and Testing Libraries

In your existing Next.js project directory, install Vitest and required testing libraries using following command:

// Install Vitest and related packages
npm install --save-dev vitest jsdom @testing-library/react @testing-library/jest-dom

Step 2. Create Vitest Configuration

Create a vitest.config.ts file in the root folder of your project and add the following configuration:

// File - /vitest.config.ts

import { defineConfig } from 'vitest/config'

export default defineConfig({
    test: {
        environment: 'jsdom',
        globals: true,
        setupFiles: './vitest.setup.ts',
    },
})

Step 3. Add scripts in Package file

Add the following scripts in the package.json file:

// File - /package.json

{
    "scripts": {
        "test": "vitest",
        "test:ui": "vitest --ui",
        "coverage": "vitest run --coverage"
    }
}

Step 4. Create __tests__ directory

Create a __tests__ directory in the root folder of your project. Your test files should end with '.test.tsx' or '.test.jsx' extension.

Writing Tests in Next.js with Vitest

After setting up Vitest in your Next.js application, you can start writing tests for your components, hooks, and functions. In the following section, we will write a test for a Next.js home page.

Create a Next.js Component

Here's a simple Home component that we'll test. The Home component renders a welcome message and a button. When the button is clicked, it triggers an alert function.

// File - app/Home/page.tsx

export default function Home() {
    return (
        <div>
            <h1>Welcome to Next.js</h1>
            <button onClick={() => alert('Hello!')}>
                Click Me
            </button>
        </div>
    );
}

Create a Test File

Create a test file for the Home component in the __tests__ directory. The test file should end with '.test.tsx' or '.test.jsx' extension. In the following code, we are testing if the above Home component renders the welcome message and if the button click triggers the alert function.

// File - /__tests__/Home.test.tsx

import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import Home from '@/pages/index';

describe('Home Page', () => {
    it('renders welcome message', () => {
        render(<Home />);
        expect(screen.getByText('Welcome to Next.js')).toBeDefined();
    });

    it('handles button click', () => {
        render(<Home />);
        const alertSpy = vi.spyOn(window, 'alert');
        
        fireEvent.click(screen.getByText('Click Me'));
        expect(alertSpy).toHaveBeenCalledWith('Hello!');
        
        alertSpy.mockRestore();
    });
});

Run the Test

Run your tests using 'npm test' command. Vitest will execute all test files in the __tests__ directory and provide detailed output in the terminal.

Next.js Jest Testing
Advertisements