saruftw
saruftw

Reputation: 1164

Unit testing a scoped function used as a filter

I need to write a scoped function within my controller that acts as a filter.

  $scope.filterR = function(s) {

    return function(c) {
        for (var prop in c) {
          if (c[prop].toSomething() >= 0) {
            return c;
            break;
          }
        }
    }
  }

This is how I'm using it.

<div ng-repeat="c in cus | filter: filterR(s)">
        </div>

The trouble I'm facing is how to test this specific routine in karma-jasmine.

My current test looks like this,

describe('check x', function () {
    it('check abc', function () {
      var $scope = {};

      var controller = $controller('SController', {
        $scope: $scope
       });
       expect($scope.filterResults('some_data')).toEqual(
         some_data
       );
    });

The filter works fine but writing test for it giving me an issue. Any help is appreciated.

Upvotes: 1

Views: 24

Answers (1)

Estus Flask
Estus Flask

Reputation: 222319

It is always preferable to use real scopes for testing, unless it is known that it's not:

var $scope = $rootScope.$new();

filterResults is expected to return a function. So it is

var filterResultsFn = $scope.filterResults('some_data');
expect(filterResultsFn).toEqual(jasmine.any(Function));
expect(filterResultsFn(...)).toEqual(...);

Upvotes: 1

Related Questions