How do you run mocha tests in the browser?

Marco Prins picture Marco Prins · Mar 17, 2017 · Viewed 18.3k times · Source

Is it just me, or does their documentation not explain how to run the tests in the browser at all?

Do I have to create that HTML file that they show in the example? How do I make it run my specific set of test cases for my project then?

I want the same output as running mocha from project root. All subdirectories inside the test folder need to be included

Answer

Samir picture Samir · Mar 17, 2017

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="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