JavaScript : Setup testing with mocha

24 Dec 2013

Mocha is the one of the testing framework available in JavaScript. It supports both tdd and bdd and we can run tests from both browser and CLI.

Setup for testing in Browser

Every release of the Mocha will contain a mocha.js to enable testing in browser. We can use chai.js or expect.js for assertions. If you are using tdd you need mocha to setup by,

mocha.setup('tdd');

or else you can use mocha.setup('bdd'). Here is the boilerplate html for mocha testing. After including your scripts and tests, you can open up in a browser to run tests.

Don’t forget to include mocha.run() which will initiate the test runner.

<body>
    <div id="mocha"></div>
    <script src="bower_components/mocha/mocha.js"></script>
    <script>mocha.setup('bdd')</script>
    <script src="bower_components/chai/chai.js"></script>
    <script>
        var assert = chai.assert;
        var expect = chai.expect;
        var should = chai.should();
    </script>

    <!-- include source files here... -->

    <!-- include spec files here... -->
    <script src="spec/test.js"></script>

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

Setup for testing in CLI

When it comes to testing, I like CLI more than browser. So here is how you can run your mocha tests from CLI. At first you need to install npm module mocha.

npm install mocha

If you are trying to run tests of an web app in the CLI, then you need to find the help of phatomjs or else you can create some tests and try running with mocha command.

You can specify bdd or tdd using the --ui option.

Yeoman : generator-mocha

Yeoman can help you to boilerplate your mocha testing setup. Install generator-mocha for it.

npm install -g generator-mocha

Then boilerplate the setup with the command,

yo mocha

By default yeoman will generate boilerplate for bdd, if you wanna generate for tdd, use the option --ui as same as for mocha command.

Yeoman will install the mocha, chai etc with the help of bower and help to run tests with grunt-mocha. Yeoman will boilerplate for webapp and grunt-mocha will run the tests with the help of phatomjs.

If you find my work helpful, You can buy me a coffee.