Skip to content

Instantly share code, notes, and snippets.

@vqc1909a
Last active October 13, 2025 06:56
Show Gist options
  • Select an option

  • Save vqc1909a/3d2c239d3b8510a691e3b30ed947f1f9 to your computer and use it in GitHub Desktop.

Select an option

Save vqc1909a/3d2c239d3b8510a691e3b30ed947f1f9 to your computer and use it in GitHub Desktop.

Setup Vitest in Vite React Project

  1. You have to set up a react project with vite

    yarn create vite@latest
  2. You have to install the following packages

    yarn add vitest @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-event msw -D

NOTE: There will be another packages wich the project will require to install in the process such as jsdom and coverage

  1. Actualizar los scripts del package.json

    "scripts": {
      ...
      "test": "vitest",
      "test:coverage": "vitest --coverage"
    },
  2. Crear la configuración de babel vite.config.ts and vitest.setup.ts

    • vite.config.ts
        /// <reference types="vitest" />
        import {defineConfig} from "vite";
        import react from "@vitejs/plugin-react-swc";
    
        // https://vite.dev/config/
        export default defineConfig({
            plugins: [react()],
            server: {
                proxy: {
                    "/api": "http://localhost:4000",
                }
            },
            test: {
                // Use jsdom if you want maximum compatibility, stability, and are working with widely used testing tools or complex browser APIs.
                // Use happy-dom if you need faster tests, better file upload simulation, or your project relies on APIs that jsdom does not support well.
                // For most React/Vitest projects, start with jsdom. Switch to happy-dom if you encounter jsdom limitations (like file upload issues) that affect your tests.
                environment: "happy-dom",
                setupFiles: "./vitest-setup.ts",
                coverage: {
                    provider: "v8",
                    reporter: ["text", "json", "html"],
                    reportsDirectory: "./coverage",
                },
                onConsoleLog(): boolean | void {
                    return true;
                },
            },
        });
    • vitest-setup.ts
    import "@testing-library/jest-dom/vitest";
    import {beforeAll, afterEach, afterAll} from "vitest";
    import {server} from "./src/mocks/node.js";
    
    beforeAll(() => server.listen());
    afterEach(() => server.resetHandlers());
    afterAll(() => server.close());
  3. Create the respective files to set up MSW (Mock Service Worker)

    • mock/handlers.ts
        export const handlers = [
          http.get(`${BACKEND_URL}/api/files`, async ({request}) => {
              await delay(300);
                  const url = new URL(request.url);
              const query = url.searchParams.get("q");
              if(!query){
                return HttpResponse.json({message: "Query param 'q' is required"}, {status: 400});
              }
                  const filteredData = userData.filter(row => {
                      return Object.values(row).some((value) => value.includes(query.toLowerCase()));
                  });
    
                  return HttpResponse.json({message: "Data retrieved successfully", body: filteredData});
              }),
          ];
    • mock/node.ts
      import {setupServer} from "msw/node";
      import {handlers} from "./handlers.js";
    
      export const server = setupServer(...handlers);
  4. And you are ready to begin with your first test case

      import {describe, test, expect} from "vitest";
      import {render} from "@testing-library/react";
      import App from "../App";
    
      describe("Tests in App.tsx", () => {
        test("should render App component", () => {
          const {container} = render(<App />);
          expect(container).toMatchSnapshot();
        });
      });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment