Come effettuare i test con Jest in Node.js

Jest è un framework di test sviluppato da Facebook, ampiamente utilizzato per testare applicazioni JavaScript, in particolare in ambienti Node.js e React. Questa guida mostra come configurare e scrivere test unitari con Jest in un progetto Node.js.

Installazione

Per prima cosa, crea una nuova directory per il tuo progetto ed esegui l'inizializzazione di npm:

npm init -y

Installa Jest come dipendenza di sviluppo:

npm install --save-dev jest

Configurazione

Aggiungi uno script nel tuo file package.json per eseguire i test:


  "scripts": {
    "test": "jest"
  }
  

Scrivere un Test

Crea una funzione da testare in un file, ad esempio math.js:


  function somma(a, b) {
    return a + b;
  }

  module.exports = somma;
  

Crea ora il file di test, ad esempio math.test.js:


  const somma = require('./math');

  test('somma 1 + 2 per ottenere 3', () => {
    expect(somma(1, 2)).toBe(3);
  });
  

Esecuzione dei Test

Per eseguire i test, usa il comando:

npm test

Jest rileverà automaticamente tutti i file che terminano con .test.js o .spec.js nella directory del progetto.

Conclusione

Jest rende semplice scrivere ed eseguire test unitari in Node.js. Con una configurazione minima, puoi iniziare a garantire che le tue funzioni lavorino correttamente man mano che il tuo progetto cresce.

Torna su