在 AngularJS 中使用 Jasmine 对过滤器进行单元测试

Unit-Testing a filter with Jasmine in AngularJS

我不知道如何对我的过滤器进行单元测试。其中一个示例如下所示:

angular.module('testApp')
    .filter('range', ['$log', function ($log) {
    return function (companylist, min, max) {
        max = parseInt(max, 10) || 100;
        var result = [];
        angular.forEach(companylist, function (val) {
            if (val.maxSpread >= min && val.maxSpread <= max) {
                result.push(val);
            }
        });

        return result;
    }
}]);

您如何看到过滤器迭代数组 companylist 如果最大值会改变结果 returns 一个新的公司列表。

公司对象结构如下:

{
  Id: 1,
  name: 'CompanyName',
  short: 'CN',
  maxSpread: 25
}

我不知道要测试这个过滤器。在几个教程和博客中寻找单元测试,但我没有找到任何可以帮助我的东西。

注入 $filter service,然后用它来测试您的自定义过滤器。

 describe('rage filter', function () {
  'use strict'; 

  var $filter;

  beforeEach(function () {
    module('testApp');

    inject(function (_$filter_) {
      $filter = _$filter_;
    });
  });

  it('should return a collection with maxSpread in range', function () {
    // campanies.
    var companiesList = [
        // fill you collection....
    ];

    var myExpectedCampanies = [
        // fill your expected results....
    ];

    var result = $filter('range')(companiesList , 1, 100);
    expect(result).toEqual(myExpectedCampanies);
  });
});