Introduction
This guide walks you through setting up Vitest with Next.js 14, covering the installation process and configuration steps necessary to enable testing within your Next.js application. By following these instructions and addressing common issues such as absolute imports and SVG file handling, you'll be able to seamlessly integrate Vitest into your Next.js 14 projects. Let's dive in and get testing!
Step 1
Begin by installing the required development dependencies. Choose one of the following methods:
Once the dependencies are installed, proceed to create a vitest.config.ts
or vitest.config.js
file in the root directory of your project.
Step 2
Now, configure your vitest.config.ts
file as follows:
With this configuration in place, you've completed the basic setup. However, to execute tests, you need to add a new command to your package.json
file. Add the following command under the "scripts" section: "test": "vitest"
. Now, running npm run test in your terminal should initiate the testing process. Expect to see an error indicating "no test file found" as there are currently no test files.
Step 3
Next, create a test file in your project:
Upon running this test, you may encounter an error regarding the import of "your imported file name in test file". This is due to absolute path imports in the test file conflicting with relative paths in the actual file. To resolve this, install vite-tsconfig-paths
as a development dependency:
- After installation, update your
vitest.config.ts
file as follows:
This addition resolves the absolute import error.
Addressing another common error
If your project contains SVG files, you may encounter an InvalidCharacterError
when running tests. To resolve this, install vite-plugin-magical-svg
:
Then, update your vitest.config.ts
file:
With these configurations in place, rerun the tests to verify that they now execute successfully.
Conclusion
This guide has provided a detailed walkthrough of setting up Vitest with Next.js 14. By following these steps and configurations, you can seamlessly integrate Vitest into your Next.js projects, enabling efficient and effective testing of your React components. With Vitest, you can ensure the reliability and stability of your Next.js applications. Happy testing!