测试 Filters

测试目的

  • 用单元测试测试过滤器的输入输出
  • 测试在 scope 范围的 DOM 总 Html 元素被正确处理

要测试 AngularJS 过滤器,你要用到 $injector 服务,然后从注入器中拿到 $filter 服务,然后从这开始测试调用所有你希望包含到页面的服务。过滤器可以用所有的三种方式来测试,不过每种方式都不一样。

基本上,测试一个过滤器,你也就是想看看输入输出(大多数情况下就是一个数组)。 你的 E2E 测试中,也就确认一下过滤器是否作用到了页面上。

单元测试

<!-- lang: js -->
//
// test/unit/filters/filtersSpec.js
//
describe("Unit: Testing Filters", function() {

  beforeEach(module('App'));

  it('should have a range filter', inject(function($filter) {
    expect($filter('range')).not.to.equal(null);
  }));

  it('should have a range filter that produces an array of numbers',
    inject(function($filter) {

    var range = $filter('range')([], 5);
    expect(range.length).to.equal(5);
    expect(range[0]).to.equal(0);
    expect(range[1]).to.equal(1);
    expect(range[2]).to.equal(2);
    expect(range[3]).to.equal(3);
    expect(range[4]).to.equal(4);
  }));

  it('should return null when nothing is set',
    inject(function($filter) {

    var range = $filter('range')();
    expect(range).to.equal(null);
  }));

  it('should return the input when no number is set',
    inject(function($filter) {

    var range, input = [1];
    range = $filter('range')(input);
    expect(range).to.equal(input);

    range = $filter('range')(input, 0);
    expect(range).to.equal(input);

    range = $filter('range')(input, -1);
    expect(range).to.equal(input);

    range = $filter('range')(input, 'Abc');
    expect(range).to.equal(input);
  }));

});

Midway 测试:

<!-- lang: js -->
//
// test/midway/filters/filtersSpec.js
//
describe("Midway: Testing Filters", function() {

  var tester;
  beforeEach(function() {
    tester = ngMidwayTester('App');
  });

  afterEach(function() {
    tester.destroy();
    tester = null;
  });

  it('should have a working range filter',
    function() {

    expect(tester.inject('$filter')('range')).not.to.equal(null);
  });

  it('should have a working filter that updates the DOM',
    function(done) {

    var id = 'temp-filter-test-element';
    var html = '<div id="' + id + '"><div class="repeated" ng-repeat="n in [] | range:10">...</div></div>';
    var element = angular.element(html);

    var scope = tester.rootScope().$new();
    tester.compile(element, scope);

    var elm = element[0];
    setTimeout(function() {
      var kids = elm.getElementsByTagName('div');
      expect(kids.length).to.equal(10);
      done();
    },1000);
  });

});

E2E 测试:

<!-- lang: js -->
//
// test/e2e/filters/filtersSpec.js
//
describe("E2E: Testing Filters", function() {

  beforeEach(function() {
    browser().navigateTo('/');
  });

  it('should have a filter that expands the stars properly', function() {
    browser().navigateTo('#/videos/zogrnQjHZAM');
    expect(repeater('#app-youtube-stars > .app-youtube-star').count()).toBeGreaterThan(0);
  });

});

你可能感兴趣的:(AngularJS,karma)