JavaScript
Article
By Tim Evko

Testing JavaScript with Jasmine, Travis, and Karma

By Tim Evko

Some people say that legacy code is any code written without tests, and I am one of those people. But I’m also a front-end developer, which means that testing my code often requires a browser. This makes testing slightly more difficult, or at least I thought it was. In reality, it’s actually quite simple and in this article I’ll show you what it takes to get started!

GitHub and Travis CI

In order to test our code, we’re going to use GitHub and Travis CI. GitHub will host our code, and Travis CI will serve as the testing platform. This is all completely free for public repositories, and there’s plenty of documentation to help you in using both these products. The first thing to do is to create a repository on GitHub. For the sake of this tutorial, I’ve created a repository that you can find here.

The next step is to visit the page at https://travis-ci.org/ and sign in with GitHub. Once done, you’ll need to add a repository for Travis to run tests against as shown in the image below.

add new repository

Clicking on the “plus” icon will take us to a console where we can sync with our GitHub account and choose the repository.

selecting repository

The dashboard for our repository will be blank since we haven’t set up any test. Let’s now move to the next stage.

Doing Stuff with Node.js

Just like Mitochondria is the powerhouse of the cell, Node.js is going to be the powerhouse of our sweet testing setup. If you haven’t installed Node.js, visit its website and install it. Once done, clone the repository you created in the previous section so that you have all the files in your local machine. At this point, we’re ready to install Karma!

Karma is a testing framework originally created by the AngularJS team. We’re going to use it to help us run Jasmine on Travis CI in Firefox. I know that sounded overwhelming, but don’t worry! Soon we’ll have some really cool tests running and it’ll all be worth it.

If you don’t have already a package.json file and the node_module folder in your repository, run npm init and complete the setup. The previous command will help you in creating the package.json file. Next, run the following command:

npm install karma --save-dev

We’re also going to install a few necessary Karma plugins: karma-jasmine and karma-firefox-launcher. So go ahead and run:

npm install karma-jasmine karma-firefox-launcher --save-dev

Now that we have all of the necessary plugins installed, we want to tell Karma about our project so that it can run tests against it. Run the command:

karma init my.conf.js

This will take you through a guided setup, asking you questions about your project and its environment. The following screenshot will show all of the required questions and answers for a simple Karma setup:

karma init

We haven’t yet created our test directory. So, when asked about the location of our source and test files, we’ll be warned that tests/*.js doesn’t exist. As for dist/*.js, that’s the file that I plan to run my tests against, which may be different for your project.

That’s it! Karma is good to go!

Configuring Travis

So far, Travis has no idea what to do with our repository. Let’s fix this. We’ll need to create a .travis.yml file with the following code:

language: node_js
node_js:
    - "0.10"
script: node_modules/karma/bin/karma start my.conf.js --single-run
before_install:
    - export DISPLAY=:99.0
    - sh -e /etc/init.d/xvfb start
before_script:
    - npm install

This tells Travis that we’re using Node.js to test JavaScript and use Firefox as a browser. Besides, we specify that before it begins testing, it should run npm install to grab all of the necessary plugins.

--ADVERTISEMENT--

Writing Tests with Jasmine

Up to this point, we have Karma and Travis properly configured. So, we’re ready to write some tests for our JavaScript code. For my sample repository, I have a file called coolLibrary.js that adds a teal square to the body element and gives it a data attribute. You can see it in action on CodePen.

In order to test this code, I’ve created the tests directory mentioned in the my.conf.js file, and from there I’ll add the jasmine test files. My first test will be a simple check to ensure that there is a div on the page with a class of box. Jasmine makes this very simple with an easy-to-understand function syntax. Here’s what the first test (checkIfDivExists.js) looks like:

describe('getDiv', function() {
    var d = document.querySelector('.box');

    it('Should exist', function() {
        expect(d.nodeName).toBe('DIV');
    });
});

This creates a Suite that searches for an element with the class of box, and expects its node name to be DIV. The syntax is pretty straightforward.

In addition to the previous test, I’ll also create two more tests that you can find in the GitHub repository for this project and that are copied below for your commodity:

describe('getDivBg', function() {
    var d = document.querySelector('.box');

    it('Should be teal', function() {
        expect(d.style.backgroundColor).toBe('teal');
    });
});

describe('getDivAttribute', function() {
    var d = document.querySelector('.box');

    it('Should be bar', function() {
        expect(d.getAttribute('foo')).toBe('bar');
    });
});

Running the Tests

With the tests for our code in place, our final step is to commit our code. This will add all of our testing logic and trigger a build on Travis. Don’t forget to have a .gitignore file that ensures your node_modules folder isn’t pushed into the repository! Once you commit and push your code, Travis will automatically detect the changes and run your tests. The process may take a few minutes, but you’ll be alerted via email as soon as the build is complete.

Success!

successful build

You can create as many tests as you need, and GitHub will make sure to check incoming pull requests against these tests as well.

Conclusion

In this tutorial we learned how to set up a simple testing environment for our JavaScript code using Karma, Jasmine, and Travis. Feel free to see the final result at https://github.com/sitepoint-editors/FEJStesting and sound off with any questions or concerns in the comments! You can view the latest test on Travis at https://travis-ci.org/tevko/FEJStesting

  • davecranwell

    It’s a minor point but as someone who only recently go into this stuff, I’ve been frustrating by tutorials never explaining what Karma and Jasmine actually are, what they provide, only that you should use them. It could do with at least a one-liner explanation. “Karma is a testing automation system, Jasmine is the framework in which you write the tests themselves”.

    • Tim

      My apologies Dave. You’re right, and while I tried to simplify all of this as much as possible, I missed that one liner. Hopefully, aside from all that, the article is still helpful for beginners. Thanks for the valuable feedback!

  • Thank you for the article, it is very clear and well written. I’ve tried to follow your instruction, and all was going well until the last command karma init my.conf.js. The system tells me that the karma command does not exist.
    The strange thing is that I’ve tried both in windows and Linux Ubuntu, and I get the same identical error. I think that I’m probably missing some passage here, or maybe you forgot to explain something?

    • James Hibbard

      Hi, try installing karma-cli:
      npm install -g karma-cli
      This is the Karma command line interface and you need to install this module if you want to be able to use karma from your command line.

  • Tim, thank you again for this fantastic guide which has been incredibly helpful to me. I got the same final result as you in Travis with my build but there’s something that I don’t quite understand regarding the build results. Toward the end of the your build result that I can see on Travis there’s this message

    Firefox 31.0.0 (Linux): Executed 0 of 3 SUCCESS (0 secs / 0 secs)

    Why it says executed 0 of 3? Doesn’t that mean that no test has been executed?
    When I run the tests on my local install I get a message saying ‘executed 1 of 1’ which is more logical to me but in Travis I get the same message as you (executed 0 of 1). I think that there’s a problem somewhere, what do you think?

    • Tim

      Yes, while the tests are running, the reporting of those tests (0 of N) is broken. Try sending up a test that purposely fails, you’ll see that everything works as expected! There’s a github issue out there somewhere about this very bug.

      • After writing here I had the idea of adding a failing test as you suggest, and in fact it behaved as expected, confirming that the tests are executed, Thank you anyway for letting me know that it is a bug

  • i really enjoyed reading this article, thank you

  • Kulwinder Kaur

    Hi
    We are developing UWP app using angularJS and winJS for windows 10 using visual studio 2015. We are unable to test winRT apis using jasmine and chutzpah since chutzpah runs on a headless browser. How can we unit test our windows native features e.g. windows.storage.fileio etc. Please do give a reply. we will be highly thankful.

  • Axe Effect

    Hi Tim, thank you for your knowledge. However I am surprised by the fact the tutorial actually does not test any kind of JavaScript code. The three Jasmine ‘describe’ tests you have presented the only thing the do is to test the integrity of a static DOM, but they do not test JavaScript logic like a function or the result of a variable or DOM change after some JavaScript code has been executed.

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.