w3resource

Running Mocha in the broweser


In the previous tutorials we have used mocha via node. However, in this tutorial we will look at the support that exists for mocha on the browser.

Mocha can run in the browser. Every release of Mocha has new builds of ./mocha.js and ./mocha.css for you to use in the browser.

Browser-specific methods

Browser-specific methods are method(s) that only function in a browser context:

mocha.allowUncaught() :if it is called, the uncaught errors are not absorbed by the error handler.

A typical setup may look something like the following, where you call mocha.setup('bdd') in order to use the BDD interface before loading the test scripts, running them will onload with mocha.run().

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Mocha Tests</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
  </head>
  <body>
    <div id="mocha"></div>

    <script src="https://unpkg.com/chai/chai.js"></script>
    <script src="https://unpkg.com/mocha/mocha.js"></script>

    <script class="mocha-init">
      mocha.setup('bdd');
      mocha.checkLeaks();
    </script>
    <script src="test.array.js"></script>
    <script src="test.object.js"></script>
    <script src="test.xhr.js"></script>
    <script class="mocha-exec">
      mocha.run();
    </script>
  </body>
</html>

GrepP

The browser can use the --grep as functionality. You should append a query-string to your URL: ?grep=api.

Browser configuration

You can set mocha options via mocha.setup(). Examples:

// you should use "tdd" interface.  it is a shortcut to setting the interface;
// any other options have to be passed via an object.
mocha.setup('tdd');

// This is equivalent to the above method.
mocha.setup({
  ui: 'tdd'
});

// you should use "tdd" interface, check for global leaks, and then force all tests to be asynchronous
mocha.setup({
  ui: 'tdd',
  checkLeaks: true,
  asyncOnly: true
});

Browser-specific option(S)

Browser Mocha has many cli options but not all Mocha options are cli options.

If you want to use a cli option that contains a "-", you need to convert the option to camel-case, (eg. check-leaks to checkLeaks).

Options which differ slightly from cli options:

reporter {string|constructor}

You can pass a custom reporter's constructor or a reporter's name. you can use built-in reporters as well. Their employment in browsers is neither supported or recommended, you can open the console to see the test results.

Options that only function in browser context:

noHighlighting {boolean}

If you set this to true, you should not attempt to use syntax highlighting on output test code.

Reporting

The "html" reporter is the default reporter when you are running Mocha in the browser. It will look like this:

mocha reporting


Inviting useful, relevant, well-written and unique guest posts