How do you run mocha tests in the browser?

If we need to run our tests in a browser, we need to set up a simple HTML page to be our test runner page. The page loads Mocha, the testing libraries and our actual test files. To run the tests, we’ll simply open the runner in a browser.

example html code :

<!DOCTYPE html>
<html>
  <head>
    <title>Mocha Tests</title>
    <link rel="stylesheet" href="https://stackoverflow.com/questions/42857778/node_modules/mocha/mocha.css">
  </head>
  <body>
    <div id="mocha"></div>
    <script src="node_modules/mocha/mocha.js"></script>
    <script src="node_modules/chai/chai.js"></script>
    <script>mocha.setup('bdd')</script>

    <!-- load code you want to test here -->

    <!-- load your test files here -->

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

Setting up a Directory Structure

You should put your tests in a separate directory from your main code files. This makes it easier to structure them, for example if you want to add other types of tests in the future (such as integration tests or functional tests).

The most popular practice with JavaScript code is to have a directory called test/ in your project’s root directory. Then, each test file is placed under test/someModuleTest.js.

Important things :

  • We load Mocha’s CSS styles to give our test results nice formatting.
  • We create a div with the ID mocha. This is where the test results are
    inserted.
  • We load Mocha and Chai. They are located in subfolders of the
    node_modules folder since we installed them via npm.
  • By calling mocha.setup, we make Mocha’s testing helpers available.
  • Then, we load the code we want to test and the test files. We don’t
    have anything here just yet.
  • Last, we call mocha.run to run the tests. Make sure you call this
    after loading the source and test files

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)