RyanJM

Testing an Ember.js App

· · Dev

When developing in Rails, I preferred TDD and wanted to apply the same approach to an Ember.js project. Although Ember uses QUnit, initial setup proved challenging. After discovering Jo Liss's presentation on testing Ember apps, I adopted Konacha, a testing framework built for Rails that combines Mocha and Chai.

Load the whole thing or parts in isolation?

I consulted with Jo Liss and learned she loaded the entire Ember.js app. To implement this approach, a spec_helper.js file replicates the files loaded by application.js. The key modification involves putting the app into testing mode:

Ember.testing = true;
App = Ember.Application.create();

Tests require three components: the spec_helper requirement, a before callback creating an app instance, and an afterEach callback resetting the app.

Fixtures

To maintain DRY principles, I created a fixtures directory under spec/javascripts. Objects must be wrapped in functions to control when they're created:

function myModelFixture() {
  App.adapter.load(App.store, App.MyModel, {
    id: 1,
    name: "Hello World"
  });
};

Loading Data

Since Konacha runs in the browser, Ember Data models must be created for testing. Initial attempts using App.MyModel.createRecord() worked for simple models but failed with embedded objects. The solution required App.adapter.load(App.store, App.MyModel, {...}).

With this setup complete, I could confidently test models.