Testing ember components with Ember-QUnit

In this blogpost I am going to show you how to test your components using ember and ember-qunit.
I am assuming that you are familiar with ember-cli as we’re going to be using it.

In this example my component name will be show-products.js under app/components/show-products.js and template is under app/templates/components/show-products.js.

So we have imported moduleForComponent which is an ember-qunit helper to load your component, show-products, for us. Once we have it defined we can then access the component using the this.subject() within the test function and we cat get/set values or send actions to it.

It also allows us to get the currentElement by doing: this.$()

One tricky bit is that the Ember Run Loop is disabled when testing your app so that is why we need to call it ourselves.


import Ember from "ember";
import { test, moduleForComponent } from "ember-qunit";
moduleForComponent("show-products");
test('should not show products for the first time', function() {
var component = this.subject();
equal(component.get('showingProducts'), false);
});
test('should show products when clicked on link', function() {
var component = this.subject();
Ember.run(function() {
component.send('toggleElement');
})
equal(component.get('showingProducts'), true)
});
test('shows one product', function() {
var component = this.subject();
Ember.run(function() {
component.set('products', [ 'Remote Control']);
component.send('toggleElement');
});
equal(this.$().find('ul li').length, 1)
});
test('shows multiple products', function() {
var component = this.subject();
Ember.run(function() {
component.set('products', [ 'Remote Control', 'AAA Battery']);
component.send('toggleElement');
});
equal(this.$().find('ul li').length, 2)
})


<p class="intro smaller">Products <a href="#">See all</a></p>
<div class="products">
{{#if showingProducts}}
<ul>
{{#each products}}
<li>{{.}}</li>
{{/each}}
</ul>
{{/if}}
</div>


import Ember from "ember";
export default Ember.Component.extend({
showingProducts: false,
toggleElement: function() {
this.toggleProperty('showingProducts');
}
});


{{show-products products=products}}

view raw

template.hbs

hosted with ❤ by GitHub

Also, as you may have noticed in the show-products.hbs template I have used {{.}} instead of this that is why Handlebars binds . to this for us.

That is it, very straight forward isn’t it?

Thanks

Leave a comment