简体   繁体   English

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

[英]Unit-Testing a filter with Jasmine in AngularJS

I don't know how to unit testing my filters. 我不知道如何对过滤器进行单元测试。 One of the examples are shown below: 示例之一如下所示:

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;
    }
}]);

How you can see the filter iterates an array companylist and if the max value will changed the result returns a new list of company. 怎么可以看到过滤器遍历数组companylist如果最高值将改变结果返回公司的一个新的列表。

The company object is structured as follows: 公司对象的结构如下:

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

I have no idea to test this filter. 我不知道要测试此过滤器。 Looking for a unit test at several tutorials and blogs but I've not found anything what could help me. 在几个教程和博客中寻找单元测试,但是我找不到任何可以帮助我的东西。

Inject $filter service , and, use it to test your custom filter. 注入$ filter服务 ,然后使用它来测试您的自定义过滤器。

 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);
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM