英文原文:http://emberjs.com/guides/testing/testing-routes/

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

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

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

  1. App.ApplicationRoute = Em.Route.extend({
  2. actions: {
  3. displayAlert: function(text) {
  4. this._displayAlert(text);
  5. }
  6. },
  7. _displayAlert: function(text) {
  8. alert(text);
  9. }
  10. });

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

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

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

  1. moduleFor('route:application', 'Unit: route/application', {
  2. setup: function() {
  3. originalAlert = window.alert; // store a reference to the window.alert
  4. },
  5. teardown: function() {
  6. window.alert = originalAlert; // restore original functions
  7. }
  8. });
  9. test('Alert is called on displayAlert', function() {
  10. expect(1);
  11. // with moduleFor, the subject returns an instance of the route
  12. var route = this.subject(),
  13. expectedText = 'foo';
  14. // stub window.alert to perform a qunit test
  15. window.alert = function(text) {
  16. equal(text, expectedText, 'expected ' + text + ' to be ' + expectedText);
  17. }
  18. // call the _displayAlert function which triggers the qunit test above
  19. route._displayAlert(expectedText);
  20. });

在线示例

自定义测试助手