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

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

最佳答案

过滤器为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(...);

10-08 16:55