Unit tests are used to test smaller chunks of functionality. In this recipe, we'll see an example of this.
In this example, we'll create a simple Ember.Object
with a computed property. We'll test this computed property and assert if the value returned is correct or not.
first-last.js
file in the models
folder:// app/models/first-last.js import Ember from 'ember'; export default Ember.Object.extend({ firstName: 'John', lastName: 'Smith', fullName: Ember.computed('firstName', 'lastName', function() { const firstName = this.get('firstName'); const lastName= this.get('lastName'); return `Full Name: ${firstName} ${lastName}`; }) });
In this file, we have two properties, firstName
and lastName
. The fullName
computed property combines these two and returns a full name. If either of these properties change, the computed property will fire.
Ember.Object
and computed
property:$ ember g model-test first-last
The model-test
unit test generated will create a new test file in the /tests/unit/models
directory.
first-last-test.js
file with a new unit test that checks to see whether the computed property is returning the correct values:// tests/unit/models/first-last-test.js import { moduleFor, test } from 'ember-qunit'; moduleFor('model:first-last', 'Unit | Model | fullName', { unit: true }); test('check computed property fullName', function(assert) { const firstLast= this.subject(); firstLast.set('firstName','Erik'); firstLast.set('lastName','Hanchett'); assert.equal(firstLast.get('fullName'), 'Full Name: Erik Hanchett'); });
The moduleFor
is a unit test helper provided by ember-qunit
. This helps us get access to the model that we created for lookup and instantiation. The unit: true
property flags the test case as a unit test. As we are using moduleFor
, we can instantiate the firstLast
object using this.subject()
. The test then sets firstName
and lastName
of the computed properties and does assert
to make sure that they are equal.
ember server
and check the output of the /tests
URL:first-last-test.js
file with the wrong value:// tests/unit/models/first-last-test.js … test('check computed property fullName', function(assert) { const firstLast= this.subject(); firstLast.set('firstName','Erik'); firstLast.set('lastName','Hanchett'); assert.equal(firstLast.get('fullName'),'Full Name: Erik wrong'); });
We updated the code, so now the test will fail because the text does NOT match.
/tests
folder and see the output:Now the test fails because the text does not match. You can see this output by navigating to the /tests
folder or running ember test
from the command line.