Setup Guide: Writing Tests in NextJS with Vitest
Introduction
Vitest is a modern testing framework built on Vite. It boasts incredibly fast execution speed by leveraging worker threads, perfect compatibility with the Jest ecosystem (in terms of syntax and API), and excellent support for TypeScript/JSX without complex configuration.
In this article, I will guide you on writing unit tests, component tests, and integration tests.
- Unit Test: Checks independent functions or logic to ensure they work correctly with different inputs.
- Component Test: Checks the user interface and interactions of individual components.
- Integration Test: Checks the coordination between multiple components or between the client and the API (often mocked) to ensure smooth business logic flow.
Prerequisites
This article is implemented on a NextJS project, please initialize a project before continuing.
Detail
I will continue using content from the Demo AI Agent article to write tests for it, but will need to refactor the code to better support testing as follows:
Create file app/chatbot/type.ts
Create file app/chatbot/util.ts
Create file app/chatbot/useChat.ts
The custom hook useChat manages Socket.io connection logic and API calls. It handles loading the initial conversation list, sending user messages, and listening to real-time AI responses, including processing steps.
Create file app/chatbot/page.tsx
The ChatPage is the main interface that displays the conversation list and the chat frame. This component integrates data-testid attributes to serve part identification when running tests and automatically scrolls down when new messages arrive.
Next, please install the following necessary packages:
- vitest: Main testing framework.
- @vitejs/plugin-react: Plugin that helps Vitest understand React syntax.
- @vitest/ui: Intuitive dashboard interface to monitor test results.
- @vitest/coverage-v8: Use for test coverage.
- @testing-library/dom & jsdom: Simulates a browser environment in Node.js to test components.
- msw (Mock Service Worker): A tool to intercept and mock API requests for Integration Testing.
Create file vitest.setup.ts
This file configures the global test environment, including adding matchers from @testing-library/jest-dom, mocking browser functions that JSDOM does not yet support like matchMedia and scrollTo, and simultaneously mocking the socket.io-client library to avoid real network connection errors when testing.
Create file vitest.config.ts
- This configuration file defines how Vitest operates: using the React plugin, setting up the jsdom environment, enabling global variables like describe, it, expect without importing them, and specifying the setup file created in the previous step.
- Note that we have not done end-to-end testing in this article (I will guide later) so will exclude the file formats related to e2e beforehand.
Next are the test files
Create file test/ChatBot/unit.test.ts
This code performs a Unit Test for utility functions. It checks whether the createMessage function creates the correct data object and whether the updateMessages function adds new messages to the list while still maintaining immutability.
Create file test/ChatBot/component.test.tsx
The code performs a Component Test for ChatPage. It mocks the useChat custom hook to control input data and checks whether when the user enters text and presses the send button, the sendMessage function is called with the correct parameters.
Create file test/ChatBot/integration.test.ts
This is an Integration Test using MSW to mock a real API server. The test checks whether when the custom hook useChat is initialized, it automatically calls the API to get the conversation list and updates the data state successfully.
Please add the following commands to the package.json file:
- test:vi: Runs Vitest in watch mode (automatically restarts when code changes).
- test:ui: Opens the Vitest Dashboard interface on the browser for intuitive results.
- test:run: Runs all tests once (commonly used in CI/CD).
The test results are as follows:
Dashboard as follows:
Happy coding!
Comments
Post a Comment