Vitest + React Testing Library

462
0

Vite si è ormai dimostrato essere un ottimo sostituto ad altri strumenti come create-react-app o create-vue, ma come possiamo testare, ad esempio, i nostri componenti React come avremmo fatto grazie a Jest + React Testing Library in un applicativo creato con create-react-app?

Ti presento…

*Rullo di tamburi*

vitest

Vitest non è altro che il nostro sostituto a Jest, ovvero un test runner che, grazie alla sua integrazione nativa con Vite, ci permetterà di eseguire la nostra suite di test in modo comodo e veloce.

Andiamo quindi a vedere come!

TL;DR e relativo repository disponibile qui!


Setup

Prima di tutto dobbiamo creare la nostra applicazione Vite, eseguiamo quindi i seguenti comandi

yarn create vite vitest-example --template react-ts
cd vitest-example
yarn install

Andiamo inoltre a installare alcuni pacchetti NPM che saranno utili per creare ed eseguire i nostri test

yarn add axios
yarn add -D @testing-library/jest-dom @testing-library/react jsdom vitest

Siamo pronti per iniziare!


Creazione dell’applicazione

Il risultato che raggiungeremo, andando a copiare e incollare i file sottostanti, sarà all’incirca questo:

Complicato eh?

Prima di tutto, andiamo a creare un hook che ci ritornerà il numero di Pokémon attualmente esistenti

import {useEffect, useState} from "react";
import axios from "axios";

export const usePokemonCount = () => {
    const [count, setCount] = useState(0)

    useEffect(() => {
        axios.get("https://pokeapi.co/api/v2/pokemon?limit=1").then(res => {
            setCount(res.data.count)
        })
    }, [])

    return count;
}

Quest’hook non fa altro che, una volta renderizzato, eseguire una richiesta alle pokeapi, recuperare il numero di Pokémon presenti dalle API e ritornare il valore presente nella variabile count.

Andiamo anche a modificare il file App.tsx

import './App.css'
import {usePokemonCount} from "./hooks/usePokemonCount";

function App() {
  const count = usePokemonCount()

  return (
    <div className="App">
      <h1>Se proprio devi sapere quanti pokemon esistono</h1>
      <div className="card">
        Esistono {count} pokemon attualmente
      </div>
    </div>
  )
}

export default App

E siamo pronti a testare!


Vitest

Prima di scrivere il nostro test dobbiamo configurare il nostro progetto per funzionare con Vitest, andiamo quindi a creare un file setupTests.ts con l’import di jest-dom, che ci permetterà di effettuare asserzioni rispetto al DOM renderizzato.

import "@testing-library/jest-dom";

E andiamo a modificare il nostro vite.config.ts utilizzando l’import di defineconfig da vitest/config e aggiungendo nella sezione test delle utilities che ci permetteranno di vedere ed eseguire i nostri test con jsdom.

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: "./src/setupTests.ts",
  }
})

Scriviamo quindi il nostro primo test!

Un test scritto con Vitest non devia molto da un test che scriveremmo con Jest, andiamo a creare il file App.test.tsx con il seguente contenuto

import {vi} from "vitest"
import * as hooks from "./hooks/usePokemonCount";
import {render} from "@testing-library/react";
import App from "./App";

describe('Dato che voglio sapere quanti pokemon esistono', function () {
    it('dovrebbe stampare il numero corretto ritornato dalle api', function () {
        vi.spyOn(hooks, "usePokemonCount").mockReturnValue(10)

        const {getByText} = render(<App />)

        expect(getByText("Esistono 10 pokemon attualmente")).toBeInTheDocument()
    });
}); 

Andiamo ad analizzare pezzo per pezzo quello che fa il test:

  • Prima di tutto esegue l’equivalente di jest.spyOn sul nostro hook grazie a vi, un utility di Vitest.
  • Dopodiché utilizziamo il metodo render della React Testing Library per renderizzare il nostro componente
  • Infine andiamo a controllare che il testo “Esistono 10 Pokémon attualmente” sia presente nel DOM renderizzato.

Ora non ci resta che eseguire il test, per far ciò andiamo a modificare il nostro file package.json e aggiungiamo uno script per eseguire i test:

{
  "name": "vitest-example",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest run" // Aggiungiamo questo script!
  },
  "dependencies": {
    "axios": "^0.27.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    ...
  }
}

Eseguiamo quindi uno yarn test e…

Magia delle magie!

Il nostro test funziona!

Ora hai a disposizione gli strumenti per scrivere dei test con Vitest e React Testing Library, ma se vuoi fare ancora un passettino in più, andiamo a installare anche Vitest UI!


Vitest UI

Difficile a credersi, ma Vitest ci fornisce oltre a un ottimo modo per scrivere ed eseguire i test, anche una UI per vedere i risultati senza dover controllare il noiosissimo terminale!

Per installare la Vitest UI andiamo a installare il pacchetto @vitest/ui

yarn add -D @vitest/ui

Aggiungiamo anche lo script per eseguire il comando corretto nel nostro package.json

{
  "name": "vitest-example",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "preview": "vite preview",
    "test": "vitest run",
    "test:ui": "vitest --ui" // Aggiungiamo questa riga!
  },
  "dependencies": {
    "axios": "^0.27.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    ...
  }
}

Ed eseguiamo il comando yarn test:ui, dove potremo vedere, grazie alla magia di Vitest UI, i nostri test con relativi log, albero delle dipendenze e altro ancora!

E questo è quanto!

Grazie e alla prossima!

Leave a Reply

Your email address will not be published. Required fields are marked *