How to unit test a filter in AngularJS 1.x

后端 未结 5 1446
深忆病人
深忆病人 2020-12-25 10:26

How do you unit test a filter in Angular?

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 11:25

    Here you have a runnable filter test example.

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

    Note: this answer was created after the SO Documentation Sunset based on the AngularJS unit test filter example and a suggestion on Meta that all valuable documentation content should be converted into answers.

提交回复
热议问题