简体   繁体   中英

Testing angular services with controllers

I have my custom angular service, which has one method that handles with $scope.$watch , is it possible to unit test it?

angular.module('moduleName', []).factory('$name', function () {
  return {
     bind: function ($scope, key) {
       $scope.$watch(key, function (val) {
         anotherMethod(key, val);
       }, true);
     },
     ...
  };
});

Solution that I've found seems to be very easy and nice:

beforeEach(function () {
    inject(function ($rootScope) {
        scope = $rootScope.$new();

        scope.$apply(function () {
            scope.value = true;
        });

        $name.bind(scope, 'value');

        scope.$apply(function () {
            scope.value = false;
        });
    });
});

beforeEach(function () {
    value = $name.get('value');
});

it('should have $scope value', function () {
    expect(value).toBeFalsy();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM