Skip to content

Instantly share code, notes, and snippets.

@Acetoshi
Last active November 27, 2024 09:07
Show Gist options
  • Select an option

  • Save Acetoshi/8d5dbc3d2ff514ce8dd58ae26b0e4d56 to your computer and use it in GitHub Desktop.

Select an option

Save Acetoshi/8d5dbc3d2ff514ce8dd58ae26b0e4d56 to your computer and use it in GitHub Desktop.

VITEST SETUP

dependencies

on installe @testing-library/jest-dom et jsdom

npm i vitest jsdom @testing-library/react @testing-library/jest-dom --save-dev

vite.config.ts

on ajoute un élément de test

import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true, //means global variables will be available during tests like 'describe, it, expect' so we don't have to import it in every test file
    environment: "jsdom", //simulating a browser environment
    setupFiles: ["./setupTest.ts"], //execute necessary code before running the tests. This is a perfect segue to create _setupTests.ts_.
  },
});

tsconfig.json [./tsconfig.json]

Dans TS config, on rajoute qqch

  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" }
  ]
  ],
  "compilerOptions": {
    "types": ["vitest/globals", "@testing-library/jest-dom"]
  }
}

package.json

dans package-json

[...]
"test":"vitest"
[...]

setup [./setupTest.ts]

On fait un fichier setup config (l'emplacement doit correspondre à celui dans vite.config) doc ici : https://vitest.dev/config/#setupfiles

import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";
import "@testing-library/jest-dom";

// runs a clean after each test case (e.g. clearing jsdom)
afterEach(() => {
  cleanup();
});

component.test.tsx [ ./src/component/component.test.tsx ]

ensuite on fait des fichiers à coté des composants , en .tsx pour avoir accès aux composants

import { screen, render } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import "@testing-library/jest-dom";
import Title from "./Title";

describe("Test de mon composant Title", () => {
  it("Should render a title", async () => {
    await render(<Title title="Vite + React" />);

    const h1 = screen.getByRole("heading", { level: 1 });
    expect(h1).toHaveTextContent("Vite + React");
  });
});

les tests sont auto détectés par vitest s'ils suivent un pattern de nommage source : https://vitest.dev/config/

include
Type: string[]
Default: ['**/*.{test,spec}.?(c|m)[jt]s?(x)']
CLI: vitest [...include], vitest **/*.test.js
A list of glob patterns that match your test files.

structure

Component/
├── Component.css             # Styles for the component
├── Component.tsx             # The component's main logic (JSX/TSX)
├── Component.types.ts        # TypeScript types for component props
└── Component.test.tsx        # Tests for the component

Workflow Github [ .github/workflows/test.yml]

name: test

on:
  pull_request:
    types: [opened, synchronize, reopened, ready_for_review]
    branches:
      - main

jobs:
  test:
    name: Run integration test on front
    runs-on: ubuntu-latest

    steps:
      - name: Check out Git repository
        uses: actions/checkout@v3

      - name: Cache dependencies
        id: cache-nextjob
        uses: actions/cache@v3
        with:
          path: |
            ./node_modules
          key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}

      - name: Install package dependencies
        run: npm i

      - name: Run Component test
        run: npm run test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment