When testing models, you can use Ember Data to help. In this recipe, we'll create a model and test to make sure that it's creating data correctly.
$ ember g model student.js
This will generate the necessary files for the student model.
// app/models/student.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string') });
This model has two properties, firstName
and lastName
. Both hold string
values.
// tests/unit/models/student-test.js import { moduleForModel, test } from 'ember-qunit'; moduleForModel('student', 'Unit | Model | student', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function(assert) { let model = this.subject(); assert.ok(!!model); }); test('Test model data', function(assert) { assert.expect(2); let model = this.subject({firstName: 'Erik', lastName: 'Hanchett'}); assert.equal(model.get('firstName'),'Erik', 'first Name is Erik'); assert.equal(model.get('lastName'),'Hanchett', 'last Name is Erik'); });
moduleForModel
helper. The first test checks whether the model is okay and it exists. The second test checks the properties:… test('Test model data', function(assert) { assert.expect(2); let model = this.subject({firstName: 'Erik', lastName: 'Hanchett'}); assert.equal(model.get('firstName'),'Erik', 'first Name is Erik'); assert.equal(model.get('lastName'),'Hanchett', 'last Name is Erik'); });
When creating the model
instance, you can pass in the values of the model
properties. In this case, the {firstName: 'Erik', lastName: 'Hanchett'}
object is created in the store. We can access these values using the model.get
method. The assert.equal
method checks against the model to make sure that the values match.
ember server
and navigate to /tests
, and you'll see the passing tests: