Unit testing methods and computed properties follows previous patterns shown in Unit Testing Basics because DS.Model extends Ember.Object.

单元测试方案和计算属性与之前单元测试基础中说明的相同,因为DS.Model集成自Ember.Object

Ember Data Models can be tested using the moduleForModel helper.

[Ember Data[模型可以使用moduleForModel助手来测试。

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.

假定有一个Player模型,模型定义了levellevelName属性。通过调用levelUp可以增加level,并当玩家升级到5级时,为levelName设置一个新的值。

  1. App.Player = DS.Model.extend({
  2. level: DS.attr('number', { defaultValue: 0 }),
  3. levelName: DS.attr('string', { defaultValue: 'Noob' }),
  4. levelUp: function() {
  5. var newLevel = this.incrementProperty('level');
  6. if (newLevel === 5) {
  7. this.set('levelName', 'Professional');
  8. }
  9. }
  10. });

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 moduleForModel:

下面创建一个测试,测试将在玩家等级为4时,调用levelUp方法来判断levelName是否正确改变。这里将使用moduleForModel来获取玩家的实例:

  1. moduleForModel('player', 'Player Model');
  2. test('levelUp', function() {
  3. // this.subject aliases the createRecord method on the model
  4. var player = this.subject({ level: 4 });
  5. // wrap asynchronous call in run loop
  6. Ember.run(function() {
  7. player.levelUp();
  8. });
  9. equal(player.get('level'), 5);
  10. equal(player.get('levelName'), 'Professional');
  11. });

Live Example

在线示例

Unit Testing Ember Data Models

Ember Data模型单元测试

Testing Relationships

测试关联关系

For relationships you probably only want to test that the relationship declarations are setup properly.

对于关联关系,可能只希望测试是否正确声明了关联关系。

Assume that a User can own a Profile.

例如一个User可以拥有一份Profile

  1. App.Profile = DS.Model.extend({});
  2. App.User = DS.Model.extend({
  3. profile: DS.belongsTo(App.Profile)
  4. });

Then you could test that the relationship is wired up correctly with this test.

这里可以对关联关系是否正确关联进行正确性测试。

  1. moduleForModel('user', 'User Model', {
  2. needs: ['model:profile']
  3. });
  4. test('profile relationship', function() {
  5. var relationships = Ember.get(App.User, 'relationships');
  6. deepEqual(relationships.get(App.Profile), [
  7. { name: 'profile', kind: 'belongsTo' }
  8. ]);
  9. });

Live Example

在线示例

Unit Testing Models (Relationships : One-to-One)

模型单元测试(关联关系:One-to-One)

Ember Data contains extensive tests around the functionality of relationships, so you probably don’t need to duplicate those tests. You could look at the Ember Data tests for examples of deeper relationship testing if you feel the need to do it.

Ember Data还包含了针对关联关系功能性测试,因此可能不需要对这些来进行重复的测试。可以查看Ember Data测试,来了解更多关于深层次的关联关系的测试。