2013-11-14 60 views
2

我正在使用Qunit和Karma進行測試,但我無法找到爲Ember組件創建測試的方法。Ember組件測試

這裏是我的測試代碼:

test('Function',function(){ 
     var test = App.MyComponent.create({ 

       data:[{'a':'a'}] 

     }); 
    var result = test.get('buildingComponent'); 
    equal(result, 'done', "function crushed because" + result); 
}); 

我的組件:

App.MyComponent = Ember.Component.extend({ 
    buildingComponent:function(){ 

     return 'done' 

    }.property('data') 

}); 

因此,如何能測試我的組件?

+0

你在這個測試中收到了一些錯誤,或者'result'只是返回undefined? –

+0

當我使用「屬性」時,結果是不確定的,當我使用「觀察」時它返回函數文本 – encore

+1

這是一個快速jsbin,顯示組件測試http://jsbin.com/UNivugu/2/edit –

回答

1

我有一個測試組件的類似問題,並在Ember測試中發現了一些讓我成功測試組件的見解。

tests for Ember's TextField顯示瞭如何編譯包含引用助手的句柄模板的一次性視圖。這使用本地創建的控制器/視圖來隔離要測試的幫助器。

這個差不多直接工作組件測試,除了我無法獲得句柄模板來解析自定義組件句柄助手名稱。我在測試中發現了一個在測試模板句柄中使用組件的方法。關鍵是引用控制器中的組件,然後使用{{view myComponentNameOnTheController ... }}插入組件。

我修改Toran的JSBin以行動表達這一點:http://jsbin.com/UNivugu/30/edit

var App = Ember.Application.create(); 

App.MyThingComponent = Ember.Component.extend({ 
    template: Ember.Handlebars.compile('<button {{action "doSomething"}}>{{view.theText}}</button>'), 

    actions: { 
    doSomething: function(){ 
     console.log('here'); 
     this.set('didSomething', true); 
    } 
    } 
}); 


///////////////////////////// 
// start of your test file 

var controller, wrapperView; 
var compile = Ember.Handlebars.compile; 

module('MyThingComponent', { 
    setup: function(){ 
    controller = Ember.Controller.extend({ 
     boundVar: "testing", 
     myComponent: App.MyThingComponent 
    }).create(); 

    wrapperView = Ember.View.extend({ 
     controller: controller, 
     template: compile("{{view myComponent theText=boundVar}}") 
    }).create(); 

    Ember.run(function(){ 
     wrapperView.appendTo("#qunit-fixture"); 
    }); 

    }, 

    teardown: function(){ 
    Ember.run(function(){ 
     wrapperView.destroy(); 
    }); 
    } 
}); 

test('bound property is used by component', function(){ 
    equal(wrapperView.$('button').text(), "testing", "bound property from controller should be usedin component"); 
}); 
1

你可以使用Qunit使用由Ryan創建的庫/插件@https://github.com/rpflorence/ember-qunit。一個簡單的例子(從上面的鏈接發佈) -

// tell ember qunit what you are testing, it will find it from the 
// resolver 
moduleForComponent('x-foo', 'XFooComponent'); 

// run a test 
test('it renders', function() { 
    expect(2); 

    // creates the component instance 
    var component = this.subject(); 
    equal(component.state, 'preRender'); 

    // appends the component to the page 
    this.append(); 
    equal(component.state, 'inDOM'); 
}); 

它使我的生活更輕鬆。希望這可以幫助。