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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Ember from "ember"; | |
export default Ember.Component.extend({ | |
showingProducts: false, | |
toggleElement: function() { | |
this.toggleProperty('showingProducts'); | |
} | |
}); |
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