Running Mocha browser tests in TeamCity

Mocha is a great javascript testing framework that supports TeamCity out-of-the-box for testing node.js-based apps on your build server. Here’s a quick guide on how to get it running in TeamCity for browser-based apps as well.

Configuring Mocha’s TeamCity reporter

First we need to configure Mocha to emit specially formatted messages to console.log() that TeamCity can detect and parse. This is easy because Mocha supports pluggable reporters for displaying test progress, and it provides a TeamCity reporter out of the box. Set this up in your mocha.html page:

<script lang="text/javascript">
		ui: 'bdd',
		reporter: function(runner) {
			// Note I am registering both an HTML and a TeamCity reporter here
			// so I can use the same HTML page for local browser development and
			// TeamCity.
			new mocha.reporters.HTML(runner);
			new mocha.reporters.Teamcity(runner);
		ignoreLeaks: true,
		timeout: 5000 // ms


Executing Mocha tests from the command line

For running our tests we will a special browser, PhantomJS, which is “headless” and has no GUI — you simply invoke it from the command line and interact with it via javascript. Here’s how you can load an HTML page containing Mocha tests — from either the local file system or a web server — passing the URL as a command-line argument:

(function () {
    "use strict";
    var system = require("system");
    var url = system.args[1];

    phantom.viewportSize = {width: 800, height: 600};

    console.log("Opening " + url);

    var page = new WebPage();

    // This is required because PhantomJS sandboxes the website and it does not
    // show up the console messages form that page by default
    page.onConsoleMessage = function (msg) {

        // Exit as soon as the last test finishes.
        if (msg && msg.indexOf("##teamcity[testSuiteFinished name='mocha.suite'") !== -1) {
    };, function (status) {
        if (status !== 'success') {
            console.log('Unable to load the address!');
        } else {
            // Timeout - kill PhantomJS if still not done after 2 minutes.
            window.setTimeout(function () {
            }, 120 * 1000);

You can then invoke your tests from the command line, and you should see a bunch of TeamCity messages scroll past.

phantomjs.exe phantomjs-tests.js http://localhost:88/jstests/mocha.html

Note in my example I am running tests on a local web server on port 81, but PhantomJS also supports local file:// URLs.

Setting up a build step for PhantomJS

Finally the last thing we need to do is to set up a new Command Line build step in TeamCity to run PhantomJS.

And that’s it! You should now see your test passes and fails showing up in TeamCity:


Thanks to Dan Merino for his original article on running Jasmine tests under TeamCity, which formed the basis for most of this post.