如何对使用其他过滤器

时间:2017-09-19 22:10:44

标签: javascript angularjs unit-testing

我在过滤器中使用过滤器。我该如何进行单元测试?

angular.module('filters')
.filter('scUrlHttp', function ($filter) {
    return function (url) {
        var result;
        var startingUrl = 'http://';
        var httpsStartingUrl = 'https://';

        if ($filter('startsWith')(url, startingUrl) || $filter('startsWith')(url, httpsStartingUrl)) {
            result = url;
        } else {
            result = startingUrl + url;
        }

        return result;
    };
});

1 个答案:

答案 0 :(得分:2)

过滤器为just services with Filter suffix

过滤器可以带有:

var filterStub;
beforeEach(() => {
  filterStub = jasmine.createSpy();
  module('app', ($filterProvider) => {
    $filterProvider.register('startsWith', () => filterStub);
  });
});

或者:

var filterStub;
beforeEach(() => {
  filterStub = jasmine.createSpy();
  module('app', { startsWithFilter: filterStub });
});

可以使用以下方法测试另一个过滤器:

var anotherFilter = $filter('scUrlHttp');

filterStub.and.returnValue(true);
expect(anotherFilter(...)).toBe(...);
expect(filterStub).toHaveBeenCalledWith(...);