Skip to content Skip to sidebar Skip to footer

How To Unit Test Views In Ember.js?

We are in the process of learning Ember.js. We do all our development TDD, and want Ember.js to be no exception. We have experience building Backbone.js apps test-driven, so we are

Solution 1:

Our solution has been to essentially load the whole application, but isolate our test subjects as much as possible. For example,

describe('FooView', function() {
  beforeEach(function() {
    this.foo = Ember.Object.create();
    this.subject = App.FooView.create({ foo: this.foo });
    this.subject.append();
  });

  afterEach(function() {
    this.subject && this.subject.remove();
  });

  it("renders the foo's favoriteFood", function() {
    this.foo.set('favoriteFood', 'ramen');
    Em.run.sync();
    expect( this.subject.$().text() ).toMatch( /ramen/ );
  });
});

That is, the router and other globals are available, so it's not complete isolation, but we can easily send in doubles for things closer to the object under test.

If you really want to isolate the router, the linkTo helper looks it up as controller.router, so you could do

this.router = {
  generate: jasmine.createSpy(...)
};

this.subject = App.FooView.create({
  controller: { router: this.router },
  foo: this.foo
});

Solution 2:

One way you can handle this is to create a stub for the linkTo helper and then use it in a before block. That will bypass all the extra requirements of the real linkTo (e.g. routing) and let you focus on the contents of the view. Here's how I'm doing it:

// Test helpersTEST.stubLinkToHelper = function() {
    if (!TEST.originalLinkToHelper) {
        TEST.originalLinkToHelper = Ember.Handlebars.helpers['link-to'];
    }
    Ember.Handlebars.helpers['link-to'] = function(route) {
        var options = [].slice.call(arguments, -1)[0];
        returnEmber.Handlebars.helpers.view.call(this, Em.View.extend({
            tagName: 'a',
            attributeBindings: ['href'],
            href: route
        }), options);
    };
};

TEST.restoreLinkToHelper = function() {
    Ember.Handlebars.helpers['link-to'] = TEST.originalLinkToHelper;
    TEST.originalLinkToHelper = null;
};

// Foo testdescribe('FooView', function() {
    before(function() {
        TEST.stubLinkToHelper();
    });

    after(function() {
        TEST.restoreLinkToHelper();
    });

    it('renders the favoriteFood', function() {
        var view = App.FooView.create({
            context: {
                foo: {
                    favoriteFood: 'ramen'
                }
            }
        });

        Em.run(function() {
            view.createElement();
        });

        expect(view.$().text()).to.contain('ramen');
    });
});

Post a Comment for "How To Unit Test Views In Ember.js?"