angularjs单元测试控制器orderBy

时间:2013-11-04 20:31:42

标签: javascript unit-testing angularjs

我有问题为我的控制器编写一个单元测试,测试orderBy在带有元素的表中。

我有advert.html:

<body ng-app="motoAdsApp" ng-controller="AdvertsController">

  <form>
    <label>Sort by</label>
    <select ng-model="sortByCol" ng-options="s.name for s in sortByCols">
      <option value=""></option>
    </select>
  </form>

  <br/>

  <table border="1">
    <tr ng-repeat="advert in adverts| orderBy:sortByCol.key">
      <td>
        <span>{{advert.countryName}}, {{advert.regionName}}</span>
      </td>
      <td>{{advert.brandName}}</td>
      <td>{{advert.modelName}}</td>
      <td>{{advert.year}}</td>
      <td>{{advert.price}}</td>
    </tr>
  </table>

</body>

controllers.js:

var motoAdsApp = angular.module('motoAdsApp', []);

motoAdsApp.controller('AdvertsController', ['$scope', function($scope) {

  $scope.sortByCols = [{
    "key": "year",
    "name": "Year"
  }, {
    "key": "price",
    "name": "Price"
  }];

  $scope.adverts = [];
  var allAdverts = ADVERTS_RESPONSE;

  $scope.filter = {
    brandName: null,
    modelName: null,
    country: null,
    region: null,
    yearFrom: null,
    yearTo: null
  };

  $scope.$watch('filter', filterAdverts, true);

  function filterAdverts() {
    $scope.adverts = [];
    angular.forEach(allAdverts, function(row) {
      if (!$scope.filter.country) {
        $scope.filter.region = null;
      }
      if ($scope.filter.brandName && $scope.filter.brandName !== row.brandName) {
        return;
      }
      // ...
      $scope.adverts.push(row);
    });
  }

}
]);

我的单元测试controllersSpec.js:

describe('MotoAds controllers', function() {

  beforeEach(function() {
    this.addMatchers({
      toEqualData: function(expected) {
        return angular.equals(this.actual, expected);
      }
    });
  });

  beforeEach(module('motoAdsApp'));

  describe('AdvertsController', function() {
    var scope, ctrl, $httpBackend;

    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET('data/adverts.json').respond(ADVERTS_RESPONSE);

      scope = $rootScope.$new();
      ctrl = $controller('AdvertsController', {$scope: scope});
    }));

  it('should sort by year', function() {
      $httpBackend.flush();

      scope.$apply(function() {
        scope.sortByCol = { key: "year"};
      });

      var prevYear = 0;
      for (var i = 0; i < scope.adverts.length; i++) {
        var advert = scope.adverts[i];
        expect(advert.year).toBeGreaterThan(prevYear);
        prevYear = advert.year;
      }
    });     

  });

});

运行我的测试后,我有这个:

Chrome 30.0.1599 (Windows Vista) MotoAds controllers AdvertsController should so
rt by year FAILED
        Expected 2010 to be greater than 2011.
        Error: Expected 2010 to be greater than 2011.
            at null.<anonymous> (D:/projects/motoads/test/unit/controllers
Spec.js:147:29)
        Expected 2009 to be greater than 2012.
        Error: Expected 2009 to be greater than 2012.

我认为元素(广告)没有排序。为什么?我该怎么做?

Plunker example (without runnable test)

1 个答案:

答案 0 :(得分:4)

orderBy过滤器在ng-repeat之类的元素上使用时,实际上并不对它过滤的数组对象进行排序。数组对象保持不变,但编译器用于创建所有html的输出数组已被修改。

所以你的$scope.adverts数组永远不会改变。它输出到视图的方式会发生变化,但不会更改数组本身。

您的单元测试的这部分看起来更像是您使用E2E测试进行测试的内容。控制器并不真正关心元素的显示方式。这对观点更负责任。控制器只关注数据是否从API中获取然后传递给视图。然后e2e测试实际上可以扫描视图并确保元素正确排序。

更新:

如果您想在测试中调用orderBy过滤器,可以使用类似于以下内容的方法执行此操作:

...
var scope, ctrl, $httpBackend, orderByFilter;
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller, $filter) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectGET('data/adverts.json').respond(ADVERTS_RESPONSE);
    orderByFilter = $filter('orderBy');
    scope = $rootScope.$new();
    ctrl = $controller('AdvertsController', {$scope: scope});
}));
...
it('should do something', function(){
    var sortedArray = orderByFilter(scope.adverts, scope.sortByCol.key);
    // do something with the sorted array here
});
...

找到了如何从javascript访问orderBy过滤器的文档here

希望有所帮助。