如何成功进行单元测试?

时间:2016-02-28 05:02:05

标签: angularjs unit-testing angularjs-directive jasmine

我正在尝试为自定义指令编写单元测试:

.directive('uiList', [
    function(scriptingService) {
      return {
        scope: {
          lengthModel: '=uiList'
        },
        link: function(scope, elm, attrs) {
          scope.$watch('lengthModel', function() {
            scriptingService.getScript(request).then(function(scripts) {
              //something
            });
          });
        }
      };
    }

我打电话给服务:

.service('scriptingService', function() {
    var scriptingService = {
      getScript: function() {
        return 'blaat';
      }
    };

    return scriptingService;
  })

我想测试是否调用了getScript方法,所以我写了这个测试;

beforeEach(inject(function($rootScope, $compile, _scriptingService_) {
    scope = $rootScope.$new();
    scope.row = 1;

    scriptingService = _scriptingService_;
    spyOn(scriptingService, 'getScript');
    element = angular.element('<ul id="rows" ui-list="row">');
    $compile(element)(scope);
    scope.$digest();
    elementScope = element.scope();
  }));

  it('should call service', function() {


    scope.$apply(function() {
      scope.row = 2;
    });

    expect(scriptingService.getScript).toHaveBeenCalled();

  });

目前我收到错误: TypeError:无法读取属性&#39; getScript&#39;未定义的。 为什么我会收到此错误以及如何解决?我以为我已经嘲笑了这项服务?

plunkr:http://plnkr.co/edit/IQOCut?p=preview

1 个答案:

答案 0 :(得分:0)

清洁版 - http://plnkr.co/edit/8SVlzG?p=preview

 beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    scope.row = 1;

    element = angular.element('<ul id="rows" ui-list="row">');
    $compile(element)(scope);
    scope.$digest();
    elementScope = element.scope();
  }));


it('should call service', function() {

    scope.$apply(function() {
      scope.row = 2;
    });

    expect(elementScope.test).toEqual(1);

  });