Quick beginner’s guide on how to use Travis CI with Github and Node.

Project Setup

Let’s setup a Node project with Unit tests:

NPM

Initialize your project with

1
$ npm init

Code

Here is the code of our app. Put it in an index.js file at the root of the project.

index.js
1
2
3
4
5
module.exports = {
add: function (a, b) {
return a + b;
}
};

Mocha

Install Mocha with NPM:

1
$ npm install mocha --save-dev

Unit Tests

Let’s write basic unit tests for our code.

Create a test folder and a index-spec.js file inside that folder.

test/index-spec.js
1
2
3
4
5
6
7
8
9
10
11
var assert = require('assert');
var calculator = require('../index');

describe('calculator', function() {
describe('add function', function() {
it('adds numbers', function () {
var result = calculator.add(1, 1);
assert.equal(result, 2);
});
});
});

Npm Script

By default, Travis will execute npm test when running tests. Let’s set the test command to mocha:

package.json
1
2
3
4
5
[..]
"scripts": {
"test": "mocha"
},
[..]

You can now run the tests with

1
$ npm test

Make sure the tests are running and passing.

Check out the full source if you run into some issues.

Setup Travis

.travis.yml

Create a .travis.yml file at the root of the project.

This file will hold the travis configuration:

.travis.yml
1
2
3
language: node_js
node_js:
- "stable"
  • language: node_js indicates to Travis that it has to deal with a JavaScript project
  • node_js: - "stable" indicates that the project should be tested against the latest stable version of Node

You can add more Node versions to the list if needed.

Integrate Travis with GitHub

At this stage, push all your project code to your GitHub repository. Go to your project Settings then Webhooks and Services. Click on Add Service and choose Travis CI:

If it is the first time you are using Travis, you will be asked to login using your GitHub Credentials.

Finish by pressing the Add Service button once more.

Add the repository to Travis

Go to travis-ci.org and on the left, click the + to add a new repository.

Sync with Github if needed and turn the current repository on.

Start a build

At this stage, a new build will be started each time changes are pushed to the repository.

If you want to trigger a build manually:

  1. Go to your repository on github
  2. Settings > Webhooks & Services > Travis CI
  3. Click the Test Service Button on the top right

Results

Go back to travis-ci.org to observe the results. If the build failed you will also receive an email.

Note on Mocha and NPM Scripts

You may have noticed that we only installed mocha locally, yet our NPM test script is simply mocha.

This is because when evaluating scripts, NPM will go an look for .bin/ executables.

In our case, NPM will effectively execute

1
$ ./node_modules/.bin/mocha

and not

1
$ mocha

I hope this will prevent any confusion.