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

发布于 2015-08-18 16:33:07 | 264 次阅读 | 评论: 0 | 来源: 网络整理

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

路由测试可以通过集成测试或者单元测试来进行。集成测试对路由的测试具有更好地覆盖性,因为路由通常用来执行过渡和数据加载,这些测试在完整上下文中更加容易测试,而独立上下文则没有那么容易。

不过有时候路由的单元测试也是非常重要的。例如,希望应用可以在任意地方都能触发一个警告。警告函数displayAlert应该被定义在ApplicationRoute中,因为所有操作或者事件都会从子路由、控制器和视图冒泡到该路由。

 
App.ApplicationRoute = Em.Route.extend({
  actions: {
    displayAlert: function(text) {
      this._displayAlert(text);
    }
  },

  _displayAlert: function(text) {
    alert(text);
  }
});
 

这使得使用moduleFor成为了可能。

在这个路由中,首先分离关注点:操作displayAlert包含了在收到操作时将调用的代码,而私有方法_displayAlert执行操作。当然可能这里代码这么简单,没有必要这么设计,但是将关注点进行分离,可以使得对于测试来说具有更好地可读性,这也有利于发现漏洞。

下面是如何对路由进行测试的示例:

 
moduleFor('route:application', 'Unit: route/application', {
  setup: function() {
    originalAlert = window.alert; // store a reference to the window.alert
  },
  teardown: function() {
    window.alert = originalAlert; // restore original functions
  }
});

test('Alert is called on displayAlert', function() {
  expect(1);

  // with moduleFor, the subject returns an instance of the route
  var route = this.subject(),
      expectedText = 'foo';

  // stub window.alert to perform a qunit test
  window.alert = function(text) {
    equal(text, expectedText, 'expected ' + text + ' to be ' + expectedText);
  }

  // call the _displayAlert function which triggers the qunit test above
  route._displayAlert(expectedText);
});
 

在线示例

自定义测试助手

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

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