Reputation: 75
I'm using Qunit and Karma for testing, but i cannot find the way to create Test for Ember component.
Here is my code for test:
test('Function',function(){
var test = App.MyComponent.create({
data:[{'a':'a'}]
});
var result = test.get('buildingComponent');
equal(result, 'done', "function crushed because" + result);
});
My component:
App.MyComponent = Ember.Component.extend({
buildingComponent:function(){
return 'done'
}.property('data')
});
So how can i test my component?
Upvotes: 2
Views: 2167
Reputation: 351
You could use the library/addon created by Ryan @ https://github.com/rpflorence/ember-qunit using Qunit. A simple example (posted from the link above) -
// 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');
});
It makes my life easier. Hope this helps.
Upvotes: 1
Reputation: 8251
I had a similar issue testing a component and found a couple of insights in the Ember tests that let me test the component successfully.
The tests for Ember's TextField
showed how to compile one-off view that includes a handlebars template that references the helper. This uses a locally created controller/view that is used to isolate the helper to test.
This almost worked directly for component testing, except I couldn't get the handlebars template to resolve the custom component handlebars helper name. I found a method for using components in a testing template handlebars in the tests for yield. The key is to reference the component in the controller and then insert the component using {{view myComponentNameOnTheController ... }}
.
I modified Toran's JSBin to show this in action: 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");
});
Upvotes: 1