入门指南 获取Ember 概念 对象模型 应用 模板 路由 组件 控制器 模型 视图 枚举 测式 配置Ember.js COOKBOOK 理解Ember.js

发布于 2015-08-18 16:42:32 | 319 次阅读 | 评论: 0 | 来源: 网络整理

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

针对控制器的单元测试使用ember-qunit框架的moduleFor来做使这一切变得非常简单。

测试控制器操作

下面给出一个PostsController控制器,控制器有一些计算属性和一个setProps操作。

 
App.PostsController = Ember.ArrayController.extend({

  propA: 'You need to write tests',
  propB: 'And write one for me too',

  setPropB: function(str) {
    this.set('propB', str);
  },

  actions: {
    setProps: function(str) {
      this.set('propA', 'Testing is cool');
      this.setPropB(str);
    }
  }
});
 

setProps设置控制器的一个属性并调用一个方法。为这个操作编写测试,需要使用moduleFor助手来设置一个测试容器:

 
1
moduleFor('controller:posts', 'Posts Controller');
 

接下来使用this.subject()来获取PostsController的一个实例,并编写一个测试来检测这个操作。this.subject()是ember-qunit库提供的一个助手方法,其返回moduleFor设置的模块的一个单例。

 
test('calling the action setProps updates props A and B', function() {
  expect(4);

  // get the controller instance
  var ctrl = this.subject();

  // check the properties before the action is triggered
  equal(ctrl.get('propA'), 'You need to write tests');
  equal(ctrl.get('propB'), 'And write one for me too');

  // trigger the action on the controller by using the `send` method, 
  // passing in any params that our action may be expecting
  ctrl.send('setProps', 'Testing Rocks!');

  // finally we assert that our values have been updated 
  // by triggering our action.
  equal(ctrl.get('propA'), 'Testing is cool');
  equal(ctrl.get('propB'), 'Testing Rocks!');
});
 

在线示例

控制器“操作”单元测试

测试控制器依赖

有时候控制器需要依赖其他控制器。这通过needs来实现。例如,下面有两个简单的控制器。PostControllerCommentsController的一个依赖:

 
App.PostController = Ember.ObjectController.extend({
  // ...
});

App.CommentsController = Ember.ArrayController.extend({
  needs: 'post',
  title: Ember.computed.alias('controllers.post.title'),
});
 

在设置moduleFor之时,需要将一个选项对象作为第三个参数,该参数是控制器的needs

 
moduleFor('controller:comments', 'Comments Controller', {
  needs: ['controller:post']
});
 

下面来写一个,测试中设置PostController中得post模型的一个属性,这个属性在CommentsController同样有效。

 
test('modify the post', function() {
  expect(2);

  // grab an instance of `CommentsController` and `PostController`
  var ctrl = this.subject(),
      postCtrl = ctrl.get('controllers.post');

  // wrap the test in the run loop because we are dealing with async functions
  Ember.run(function() {

    // set a generic model on the post controller
    postCtrl.set('model', Ember.Object.create({ title: 'foo' }));

    // check the values before we modify the post
    equal(ctrl.get('title'), 'foo');

    // modify the title of the post
    postCtrl.get('model').set('title', 'bar');

    // assert that the controllers title has changed
    equal(ctrl.get('title'), 'bar');

  });
});
 

在线示例

控制器依赖单元测试

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务