Unit Testing Ember.js: Handlebars Helpers

Filed under: Ember.js

comments (0) Views: 9,120

I've been busy building Ember.js apps for Emma and unit testing is one subject which has been coming up quite a lot. It's a concern to many in the Ember community and it seems like each team has come up with their own flavor. I wanted to take some time to document and share the approach we've decided on over at Emma.

After some research and evaluation, plus past familiarity, we decided to go with the Mocha test runner with the Expect.js assertion library. Since we were already using it in other areas, and we like the way that it integrates with Grunt to allow running tests from the command line via Grunt task, it was a no brainer.

Before we take a look at testing custom Handlebars Helpers, why not download the Github repo for this (and future) article. Ember has a number of these built in, but sometimes you just need to write your own to encapsulate a bit of functionality. The first helper formats integers into American style decimal format. 10000000 becomes '10,000,000', etc. Here's the tests running in a browser. Below is the helper.

Ember.Handlebars.registerBoundHelper('intFormat', function(num) {
    return num && num.toString().replace(/B(?=(d{3})+(?!d))/g, ",");

When using Mocha in the browser you'll start with a test harness. This is an HTML file that imports all of the pieces of Mocha and Expect, as well as the bits of code you'd like to test AND the file containing your tests. It will also contain all of your dependencies, which in our case consists of Ember and Handlebars. If you view source on the test runner page you'll see the test harness code.

Lastly, here's the test itself.

describe("Helpers", function () {
    describe("IntFormat", function () {
        it('properly formats 10000000', function() {
            var value = 10000000,
                rendered = Ember.Handlebars.helpers.intFormat._rawFunction(value),
                expected = '10,000,000';
            expect( rendered ).to.eql(expected);

The important part of this test is the _rawFunction property. Since a helper is simply a function which returns a value, we can access the _rawFunction property of our helper and execute it's codoe merely by calling it. Once you've stored the rendered value it returns, it's trivial to compare it against what you're expecting to see. Why not download the repo for this article (and future articles on Ember testing) and add some additional tests for the intFormat helper based on comments you'll find within the helper code. Give it a shot, and look forward to more articles on testing with Ember.

Amazon logo

If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!

comments powered by Disqus