Standalone Mocha with Component

05/02/2013, Thu
Categories: #JavaScript
Tags: #NodeJs

Run Mocha on the Client Side

Install Nvm to install Node by following instructions here. Nvm allows you to switch to different versions of Node to manage dependencies. Install Component after Node is properly setup from here. Component is an asset management tool for the client side. After Nvm, Node and Component are working properly, make a directory on the desktop and change to it.

# Make and Change to Directory

cd Desktop
mkdir standalone-mocha
cd standalone-mocha

Make an index.html and component.json file in the root of the folder.

# Create a HTML and JSON File

touch index.html
touch component.json

Input the following to component.json. The name can be whatever you want it to be, but the important dependencies are in the development key. Component/assert is needed because Mocha does not have an assertion library by default.

{
  "name": "a-standalone-mocha",
  "development": {
    "component/assert": "*",
    "visionmedia/mocha": "*"
  }
}

Input the following to index.html:

<!-- Html for Browser -->

<html>
  <head>
    <link rel="stylesheet" href="build/build.css" />
  </head>
  <body>
    <div id="mocha"></div>
    <div id="parent">
      <div id="child"></div>
    </div>
    <script src="build/build.js"></script>
    <script>
      assert = require("assert");
      require("visionmedia-mocha");
      mocha.setup("bdd");

      describe("Array", function () {
        describe("#indexOf()", function () {
          it("should return -1 when the value is not present", function () {
            assert(-1 === [1, 2, 3].indexOf(5));
            assert(-1 === [1, 2, 3].indexOf(0));
          });
        });
      });
    </script>
    <script>
      mocha.run();
    </script>
  </body>
</html>

Install and build with component. The -d flag is used because mocha is intended for use in development mode.

# Tell Component to Generated Files

component install -d
component build -d

Open the index.html file, and you will be greeted with the following:

Standalone Mocha with Component

Offline Demo