14

Ember.js を学習中です。私たちはすべての開発 TDD を行っており、Ember.js も例外ではありません。Backbone.js アプリをテスト駆動で構築した経験があるため、Jasmine または Mocha/Chai を使用したフロントエンド コードのテストに精通しています。

ビューをテストする方法を考えているときに、ビューが使用するテンプレートに#linkToステートメントがある場合に問題が発生しました。残念ながら、良いテストの例と実践を見つけることができません。この要点は、ember アプリケーションを適切に単体テストする方法の答えを得るための私たちの探求です。

Ember.js ソース コードの linkToのテストを確認したところ、サポートするために ember アプリの完全な接続が含まれていることに気付きました#linkTo。これは、テンプレートをテストするときにこの動作をスタブできないということですか?

テンプレート レンダリングを使用して ember ビューのテストを作成するにはどうすればよいですか?

以下は、テストの要旨と、テストに合格するテンプレート、およびテストに失敗するテンプレートです。

view_spec.js.coffee

# This test is made with Mocha / Chai,
# With the chai-jquery and chai-changes extensions

describe 'TodoItemsView', ->

  beforeEach ->
    testSerializer = DS.JSONSerializer.create
      primaryKey: -> 'id'

    TestAdapter = DS.Adapter.extend
      serializer: testSerializer
    TestStore = DS.Store.extend
      revision: 11
      adapter: TestAdapter.create()

    TodoItem = DS.Model.extend
      title: DS.attr('string')

    store = TestStore.create()
    @todoItem = store.createRecord TodoItem
      title: 'Do something'

    @controller = Em.ArrayController.create
      content: []

    @view = Em.View.create
      templateName: 'working_template'
      controller: @controller

    @controller.pushObject @todoItem

  afterEach ->
    @view.destroy()
    @controller.destroy()
    @todoItem.destroy()

  describe 'amount of todos', ->

    beforeEach ->
      # $('#konacha') is a div that gets cleaned between each test
      Em.run => @view.appendTo '#konacha'

    it 'is shown', ->
      $('#konacha .todos-count').should.have.text '1 things to do'

    it 'is livebound', ->
      expect(=> $('#konacha .todos-count').text()).to.change.from('1 things to do').to('2 things to do').when =>
        Em.run =>
          extraTodoItem = store.createRecord TodoItem,
            title: 'Moar todo'
          @controller.pushObject extraTodoItem

壊れた_テンプレート.ハンドルバー

<div class="todos-count"><span class="todos">{{length}}</span> things to do</div>

{{#linkTo "index"}}Home{{/linkTo}}

working_template.handlebars

<div class="todos-count"><span class="todos">{{length}}</span> things to do</div>
4

2 に答える 2

9

私たちの解決策は、本質的にアプリケーション全体をロードすることですが、テスト対象をできるだけ分離することです。例えば、

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/ );
  });
});

つまり、ルーターと他のグローバルが利用可能であるため、完全に分離されているわけではありませんが、テスト対象のオブジェクトに近いものについては double で簡単に送信できます。

ルーターを本当に分離したい場合は、linkToヘルパーがそれを として検索するcontroller.routerので、次のようにすることができます。

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

this.subject = App.FooView.create({
  controller: { router: this.router },
  foo: this.foo
});
于 2013-02-17T03:43:22.963 に答える
1

これを処理する 1 つの方法は、linkTo ヘルパーのスタブを作成し、それを before ブロックで使用することです。これにより、実際の linkTo の余分な要件 (ルーティングなど) がすべてバイパスされ、ビューのコンテンツに集中できるようになります。これが私がやっている方法です:

// Test helpers
TEST.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];
        return Ember.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 test
describe('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');
    });
});
于 2013-11-19T23:02:15.407 に答える