Google News
logo
Ember.js - Interview Questions
What is Testing Models in Ember.js?
Container testing methods and computed properties follow previous patterns shown in Testing Basics because DS.Model extends Ember.Object.
 
Ember Data Models can be tested in a module that uses the setupTest helper.
 
Let's assume we have a Player model that has level and levelName attributes. We want to call levelUp() to increment the level and assign a new levelName when the player reaches level 5.
 
You can follow along by generating your own model with ember generate model player.
 
app/models/player.js :
import Model, { attr } from '@ember-data/model';

export default class Player extends Model {
  @attr('number', { defaultValue: 0 }) level;
  @attr('string', { defaultValue: 'Noob' }) levelName;

  levelUp() {
    let newLevel = this.level++;
    if (newLevel === 5) {
      this.levelName = 'Professional';
    }
  }
}
Now let's create a test which will call levelUp on the player when they are level 4 to assert that the levelName changes. We will use module together with the setupTest helper method :
 
tests/unit/models/player-test.js :
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { run } from '@ember/runloop';

module('Unit | Model | player', function(hooks) {
  setupTest(hooks);

  // Specify the other units that are required for this test.
  test('should increment level when told to', function(assert) {
    const player = run(() =>
      this.owner.lookup('service:store').createRecord('player')
    );

    // wrap asynchronous call in run loop
    run(() => player.levelUp());

    assert.equal(player.level, 5, 'level gets incremented');
    assert.equal(
      player.levelName,
      'Professional',
      'new level is called professional'
    );
  });
});​
Advertisement