Getting started with mocha

getting set up and using with Travis CI

Jhey Tompkins
Caffeine and Testing

--

So you’ve written some code but what about your tests?

Testing is a strange topic. I think maybe some people have the conception that testing is taxing to set up or not worth doing on their projects. But, testing on front end projects is not hard to set up with some great options out there. Also, testing can be a sign that a project has had more care and effort put into it. That might sound a little off but in the open source world, I think you instantly take a project a little more seriously if you see evidence of well tested code and some notification of a build passing when taking a look at a project.

Two of my favorite options for getting a project tested are using mocha and Travis CI.

For those in camp TL;DR who just want some code to play with

If you just want some code and tests to hack around with you can visit a demo repo at github.com/jh3y/testPlayground. This article references the repo.

Mocha

Mocha is a great simple testing framework that runs on node.js and within the browser. It’s real easy to get set up and is real flexible in the way you use it.

note

Mocha is concerned more so with functional testing of your code and not with navigation and interaction of your project/app UI. For that style of testing I’d recommend trying out something like CasperJS.

setting up

There are quite a few steps here but all will be clear when we start writing out our simple tests.

Assuming you’re using node in your project in some fashion you will already have a package.json file in your project so go ahead and install mocha with

npm install —-save-dev mocha

This will add mocha as a devDependency to your project.

You will also want to add the following into your package.json.

“scripts”: {
"test": "make test"
}

This will come in useful when hooking into Travis CI later on.

You will want to create a Makefile by adding the file ‘Makefile’ to your project containing the following.

test:
@./node_modules/.bin/mocha -u tdd --reporter spec
.PHONY: test

This enables us to run our tests from within the root of our project directory by simply using the command

make test

You could alternatively globally install mocha with

npm install -g mocha

and run the same command as with our makefile

mocha -u tdd -—reporter spec

This option is fine but it will make your project less consumable by others straight out of the box. Also you’re going to need that makefile for Travis.

As a note, mocha will by default look for tests within a ‘test’ directory if you wondered why no path was being passed to the command.

Lastly, and optionally, if you want to use mocha-phantomjs locally which is going to be used via Travis CI later install that too with

npm install phantomjs -g
npm install -g mocha-phantomjs

options

You might have noticed that I was passing options in with my mocha command in the setting up section. -u sets the testing interface. In these tests I am using test driven development. The --reporter option will set the style of reporter you like. This is just personal preference and I like the spec reporter myself (nyan is also quite amusing). You can check out more options at the site for Mocha.

enough of that, let’s write some tests!

So we’ve got all the set up out of the way. Let’s write some simple tests.

We are going to work with a simple library that exposes a plus function that will add two numbers.

Here is the node version.

(function(){
exports = module.exports = plus = function (one, two) {
return one + two;
};
}).call(this);

Here is the browser version.

(function(){
var plus = window.plus = function (one, two) {
return one + two;
};
})();

testing out our node compatible version

We are going to write out a simple test for our node based version. This is test.js located within the test directory (We are using node’s regular assert but you can use other assertion libraries with mocha such as should.js and chai.).

(function() {
var assert = require(“assert”),
plus = require(“../lib/plus”);
suite(“plus”, function() {
test(“2 plus 3 should equals 5", function() {
return assert.equal(5, plus(2, 3));
});
});
}).call(this);

You can see in our test file that we pull in the plus lib file with require and then we have one test in place that will check that “2 plus 3 should equals 5" and sure enough when we run

make test

In the root of the project we are greeted with output telling us our test has passed!

If you’ve made it this far, well done! You have now set up a test using mocha and now you can go further and add more tests to make plus a more practical library.

For example we could add the following test that implies that plus should throw an error if either parameter is not a number,

test(“should throw error if NaN parameter”, function() {
return assert.throws((function(){
return plus(2, “string”);
}), Error);
});

Mocha will now return that a test is failing because we haven’t written the logic into our library to check parameter type.

testing our browser based version

Testing in the browser takes a little more set up but is still not hard to do. We need to set up a HTML page that will contain the browser based version of mocha, our plus lib file, and our browser tests (I grab mocha and chai using bower).

<html lang=”en”>
<head>
<title>tests : plus</title>
<link rel=”stylesheet” href=”../vendor/mocha/mocha.css”>
</head>
<body>
<div id=”mocha”></div>
<script src=”../vendor/mocha/mocha.js”></script>
<script src=”../vendor/chai/chai.js”></script>
<script>
mocha.setup(‘bdd’);
expect = chai.expect;
</script>
<script src=”../js/plus.js”></script>
<script src=”../js/test/test.js”></script>
<script>
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
} else {
mocha.run();
}
</script>
</body>
</html>

Once this page is set up, I like to have it hosted on a static server along with whatever else I am working on. But, this isn’t necessary. As we can use phantomJS and in particular mocha-phantomjs.

If you installed these two earlier, you’re all set, if not

npm install phantomjs -g
npm install -g mocha-phantomjs

Now, to run our test page with mocha-phantomjs (You simply pass the path to your test page).

mocha-phantomjs out/test/index.html

The tests being ran in here can be the same tests (adjusted to use whichever assertion library you choose). But, with it being browser based, you’ve now got access to the DOM etc. A test to take advantage of this and one I like to throw in is checking that a function or library is available, especially if you safety wrap your javascript.

describe(“plus”, function() {
describe(“plus initialization”, function() {
it(“should be available as a function”, function() {
expect(typeof window.plus).to.equal(“function”);
});
});
});

Running mocha-phantomjs, our test will pass stating that plus is indeed an available function in our page.

Once again you could extend this to check other things with our lib such as parameter type or even something like decimal points etc.

Travis CI

There has been quite a lot to digest as far but you’re nearly there.

Our last piece is Travis CI, a hosted continuous integration service for projects hosted on github. If you’re project isn’t to be hosted on github, you can certainly skip this.

Travis is real helpful and will run your tests automatically for you upon commits being made to your repos. It will then notify you of build status.

getting setup

You will first need a .travis.yml yaml file in your repo. If you are working with just a node based project, your yaml can get away with being very small.

language: node_js
node_js:
- "0.10"

By default, when your project is being built and the language is set to node_js, Travis will actually look to run the test script defined within our package.json file. In our case, this means it will run

make test

Things are a tiny bit more complex with our browser based testing dependent on what code you have in your repo. You may not want to be adding output files to your repo such as output html and test files. Fear not. In the case of our plus project, our yaml file can be more like this

language: node_js
node_js:
 — “0.10"
install:
 — npm install phantomjs -g
 — npm install -g mocha-phantomjs
 — npm install -g gulp
 — npm install -g bower
 — npm install
 — bower install
before_script:
 — phantomjs —version
 — mocha-phantomjs —version
 — gulp &
 — sleep 5 # give gulp background task some time to execute.
script:
 — mocha-phantomjs out/test/index.html
 — make test

It should be pretty self explanatory. But, for this particular project, I’ve used gulp, bower, phantomjs and mocha-phantomjs. The install section grabs all the project dependencies. The before_script section is defining what Travis needs to do just before it can run our tests/scripts. Lastly, scripts defines how to run our tests.

Once we have our .travis.yml file sorted out we need to actually set up our project in Travis. Get over to https://travis-ci.org/ and sign in with your github account. Once signed in you can then pick which projects to turn off and on for CI. Switch your project on and upon your next commit, assuming .travis.yml is present within the root of your directory, tests will be ran automatically.

One last nice touch is that you can add a build status image to your project README or wherever by grabbing the URL of the build status image on your projects individual dashboard page.

And, that’s it!

You hopefully now have a slightly better understanding of how to get set up with Mocha and TravisCI for your github projects.

Be sure to check out the project repo I set up for this at https://github.com/jh3y/testPlayground if you’d like to hack about with some tests or get a better idea of how it’s set up.

Of course, any suggestions or questions, be sure to leave a note or tweet me!

--

--