Unit test in Javascript con Mocha

Mattepuffo's logo
Unit test in Javascript con Mocha

Unit test in Javascript con Mocha

Mocha è una libreria per Javascript per eseguire unit test.

E' possibile usarla anche direttamente nel browser, cosa che faremo noi.

Quindi, nel caso specifico, non installeremo nulla, ma faremo un classico include da un CDN.

Qui sotto un esempio completo, basico, per partire:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mocha Test Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/10.2.0/mocha.min.css">
  </head>
  <body>
    <div id="mocha"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.3.7/chai.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/10.2.0/mocha.min.js"></script>

    <script>
      mocha.setup('bdd');
    </script>

    <script>
      const assert = chai.assert;

      describe('Array', function () {
        it('dovrebbe iniziare vuoto', function () {
          const arr = ['ciao'];
          assert.equal(arr.length, 0, 'L'array non è vuoto');
        });

        it('dovrebbe aggiungere un elemento correttamente', function () {
          const arr = [];
          arr.push('elemento');
          assert.equal(arr.length, 1, 'L'array non ha un solo elemento');
          assert.equal(arr[0], 'elemento', 'L'elemento aggiunto non è corretto');
        });
      });
    </script>

    <script>
      mocha.run();
    </script>
  </body>
</html>

Ovviamente guardate la documentazioni per esempi più concreti.

Enjoy!


Condividi

Commentami!