如何在AngularJS 1.x中对过滤器进行单元测试


Answers:


122

注入 $filter然后用$filter('filterName')(input, options);

所以要测试这个模板的等效性 {{ foo | testFilter:capitalize }}

describe('The test filter', function () {
  'use strict'; 

  var $filter;

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

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

  it('should capitalize a string', function () {
    // Arrange.
    var foo = 'hello world', result;

    // Act.
    result = $filter('testFilter')(foo, 'capitalize');

    // Assert.
    expect(result).toEqual('HELLO WORLD');
  });
});

如果使用mocha / chai,则只需将期望值更改为:Expect(result).to.equal('HELLO WORLD');
西蒙·德拉格贝克(SimonDragsbæk)2015年

1
我不知道我是否在foo之后跟随“大写”。有人可以告诉我目的吗?
Winnemucca

1
我添加了示例模板语法,因此您可以查看其来源。最终,这只是一个过滤器参数,一些过滤器没有这些参数,但是使答案更加完整IMO
eddiec

这对我适用于chrome,但不适用于firefox或phantomjs。
artdias90

13

您可以注入$ filter并加载要测试的过滤器。然后,通过要注入的过滤器传递要过滤的参数,然后“期望”所需的参数。这是一个例子:

describe('Filter test', function(){

  var filter;

  beforeEach(function(){
    module.apply(moduleName);

    inject(function($injector){
      filter = $injector.get('$filter')('nameOfTheFilter');
    });
  });

  it('should filter the parameters passed', function(){
    expect(filter(parameterToBeFiltered)).toBe(Result);
  });
});

3

过滤器可以直接注入测试中(在此处找到了代码段)

  describe('myApp', function () {

    beforeEach(function () {
      module('myApp');
    });

    it('has a bool filter', inject(function($filter) {
      expect($filter('bool')).not.toBeNull();
    }));

    it("should return true empty array ", inject(function (boolFilter) {
      expect(boolFilter(true)).toBeTruthy();
    }));

  });

在此示例中,过滤器名称为“ bool”,要注入此过滤器,应使用“ bool” +“ Filter” =“ boolFilter”


您不应该依赖实际的代码,而是将其模拟出模块(``myApp''); 您正在调用整个应用程序,这意味着运行实际代码。
Peter MK

3

除了注入实际$filter服务之外,还有其他测试过滤器的方法。

例:

describe('FILTER: myFilterName', function(){ // You can put anything in the string here,
                                             // I like declaring FILTER: myFilterName, but it 
                                             // could be just the filter name.

var myTestTheFilterVariableName;
// This variable does not have to match the describe name, call it what you wish,
// but use this variable in any it blocks below.

beforeEach(module('obsidian')); // Include app - boilerplate.

beforeEach(inject(function(actualFilterNameFilter){
// If your test variable name is the same as 'actualFilterNameFilter' then you would 
// use this name '_actualFilterNameFilter_' with underscores; The Angularjs injector will
// remove the underscores for you.
// IMPORTANT PART: The important part here is the trailing 'Filter' name. This is how Angularjs
// Knows to grab the filter title "actualFilterName" in this case.

  myTestTheFilterVariableName = actualFilterNameFilter;

})); // This is where you actually include the filter for testing.
     // Use the underscores if your variable name is the exact same as the injected parameter.
     // This is where you would use your variable name from above.


  it('should do something here', function(){
    expect(myTestTheFilterVariableName(filterParameter)).toEqual(expectedResultHere);
  });
});

3

这里有一个可运行的过滤器测试示例。

angular.module('myModule', []).filter('multiplier', function() {
  return function(number, multiplier) {
    if (!angular.isNumber(number)) {
      throw new Error(number + " is not a number!");
    }
    if (!multiplier) {
      multiplier = 2;
    }
    return number * multiplier;
  }
});

describe('multiplierFilter', function() {
  var filter;

  beforeEach(function() {
    module('myModule');
    inject(function(multiplierFilter) {
      filter = multiplierFilter;
    });
  });

  it('multiply by 2 by default', function() {
    expect(filter(2)).toBe(4);
    expect(filter(3)).toBe(6);
  });

  it('allow to specify custom multiplier', function() {
    expect(filter(2, 4)).toBe(8);
  });

  it('throws error on invalid input', function() {
    expect(function() {
      filter(null);
    }).toThrow();
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular-mocks.js"></script>

注意:此答案是根据AngularJS单元测试过滤器示例在SO Documentation Sunset之后创建的,有关Meta的建议是所有有价值的文档内容都应转换为答案。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.