Testing models

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.

How to do it...

  1. In a new application, generate a new student model:
    $ ember g model student.js
    

    This will generate the necessary files for the student model.

  2. Update the student model with two properties:
    // 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.

  3. Add a new unit test for the new model that tests the new properties:
    // 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');
    });
  4. This test uses the 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.

  5. Run ember server and navigate to /tests, and you'll see the passing tests:
    How to do it...

    This shows that both tests passed

How it works...

The moduleForModel helper is used to access Ember's model information. This is done with Ember Data so that models can be tested. Ember's QUnit provides a way to test the module completely.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset