๐๐จ๐ฐ ๐ญ๐จ ๐ ๐๐ญ ๐ฌ๐ญ๐๐ซ๐ญ๐๐ ๐ฐ๐ข๐ญ๐ก ๐๐๐ฌ๐ญ๐ข๐ง๐ ๐ ๐ซ๐๐๐๐ญ ๐๐ฉ๐ฉ ๐ฎ๐ฌ๐ข๐ง๐ ๐๐ข๐ญ๐๐ฌ๐ญ + ๐๐๐๐๐ญ ๐๐๐ฌ๐ญ๐ข๐ง๐ ๐๐ข๐๐ซ๐๐ซ๐ฒ and ๐๐ข๐ญ๐ ๐ญ๐จ๐จ๐ฅ๐ข๐ง๐ ?
In this post, I am going to summarize how you can easily get started using cutting-edge tools to test your react/next frontend application so we are going to use ๐๐๐๐๐ญ, ๐๐ฒ๐ฉ๐๐๐๐ซ๐ข๐ฉ๐ญ, ๐๐ข๐ญ๐, ๐๐ข๐ญ๐๐ฌ๐ญ, ๐๐๐๐๐ญ ๐๐๐ฌ๐ญ๐ข๐ง๐ ๐๐ข๐๐ซ๐๐ซ๐ฒ and as you see I omitted ๐๐๐ฌ๐ญ from the setup since it needs more boilerplate for setup and because of behind scene compilation stuff it is much slower than Vitest but you donโt need to worry at all, they are almost the same in terms of 95% of their features and there is no issue about that.
1- First of all, you need to install these packages after you set up a Vite application using React library and TypeScript.
npm i vitest @testing-library/react @testing-library/user-event @testing-library/jest-dom @testing-library/dom jsdom -D
2- Create a vitest.config.ts file in the root of your project like the image below.
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
/* for example, use global to avoid globals imports (describe, test, expect): */
globals: true,
environment: "jsdom",
setupFiles: "./src/test/setup.ts",
// you might want to disable it, if you don't have tests that rely on CSS
// since parsing CSS is slow
css: false,
},
});
If you want to make some customization based on your needs, you can read the comprehensive documentation here:
3- Create a test folder in your src folder and create a file called setup.ts and add this line of code to it:
import "@testing-library/jest-dom";
By adding this we will be able to access jest functions like describe and etc in our test files.
4- Add the test script inside your package.json:
"dev": "vite",
"test": "vitest",
"coverage": "vitest run --coverage",
"build": "tsc && vite build",
"lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
๐๐จ๐ง๐ ๐ซ๐๐ญ๐ฎ๐ฅ๐๐ญ๐ข๐จ๐ง๐ฌ, ๐ฒ๐จ๐ฎ ๐๐ซ๐ ๐ ๐จ๐จ๐ ๐ญ๐จ ๐ ๐จ ๐ง๐จ๐ฐ! ๐ฐ๐๐ฌ๐งโ๐ญ ๐ข๐ญ ๐๐๐ฌ๐ฒ ๐ซ๐๐ญ๐ก๐๐ซ ๐ญ๐ก๐๐ง ๐๐๐ฌ๐ญ?!
Remember that our test runner is Vitest here but we will need to use jsdom environment and jest-dom to be able to access DOM-related functionalities inside our test files.
Now letโs write our first tests and enjoy!
I hope this could help you get started with testing your applications very fast and if so, please support by sharing.