测试AngularJS指令的惯用方法是什么?

时间:2015-11-12 22:20:24

标签: javascript angularjs testing

执行指令的内存中集成测试的惯用方法是什么?

例如,假设我有一个包含按钮的指令,当点击该按钮改变颜色时,以下是DOM集成测试的惯用语吗?

有色按钮指令-spec.js

var ColoredButtonDirective = require('../colored-button-directive');

describe('colored button', function() {

    var $compile, $rootScope;

    beforeEach(inject(function($templateCache, $rootScope, $injector) {
      // Should configuration of the module be located in the beforeEach?   
      angular.module('test', [])
            .directive('coloredButton', ColoredButtonDirective);
        $templateCache.put('./colored-button.html');            
        $compile = $injector.get('$compile'); // Can I have $compile injected instead?
    }));

    it('should turn red when clicked', function() {
        //arrange
        var dom, button;
        dom = $compile(angular.element('<colored-button></colored-button>'))($rootScope); // Must I inject a scope to the invocation of the link function?
        button = angular.element(dom.querySelector('button')); // Is there a better way of getting the button inside the rendered DOM?

        //act
        button.click();

        //assert
        expect(button.css('background-color')).toBe('red');
    });

});

有色button.html

<button ng-click='onClick'>My button</button>

着色键式directive.js

return function ColoredButtonDirective() {
    return {
        scope: {
            onClick: function($event) {
                $event.currentTarget.css('background-color', 'red');
            }
        },
        restrict: 'E',
        template: require('./colored-button.html'),
        replace: true,
    };
};

1 个答案:

答案 0 :(得分:1)

首先,在评论中解决您的问题:

// Should configuration of the module be located in the beforeEach?   
angular.module('test', [])
  .directive('coloredButton', ColoredButtonDirective);

更惯用的方式

beforeEach(module('test'));

https://code.angularjs.org/1.4.7/docs/guide/unit-testing所示。因此,从您的真实代码中实例化您的应用

var app = angular.module('test', []);

必须在测试环境中运行。

  

$ compile = $ injector.get(&#39; $ compile&#39;); //我可以注入$ compile吗?

是的,喜欢

beforeEach(inject(function(_$rootScope_, _$compile_) {
  $rootScope = _$rootScope_;
  $compile = _$compile_;
}));

将范围注入$compile

dom = $compile(angular.element('<colored-button></colored-button>'))($rootScope); // Must I inject a scope to the invocation of the link function?

是的,你必须。如果需要,您可以编译一次元素,然后链接到不同的范围,以使相同的编译版本具有不同的DOM元素。 (我认为这是ng-repeat所做的事情。

button = angular.element(dom.querySelector('button')); // Is there a better way of getting the button inside the rendered DOM?

我怀疑是的,但正如我所写,我怀疑这条线不起作用,原因有两个:

  • dom是一个jQlite对象,没有querySelector方法
  • dom是指令根目录的jQlite对象,在你的情况下是一个按钮,所以找一个按钮就找不到任何东西。

但是,如果您有不同的DOM结构,则可以执行以下操作:

button = dom.find('button');

你也没有问,但是

//act
button.click();

无法正常工作,因为jQlite没有“点击次数”。功能。你可以这样做:

dom.triggerHandler('click');

此外,

scope: {
  onClick: function($event) {
    $event.currentTarget.css('background-color', 'red');
  }
}

不会起作用,因为这并不是指针定义中scope对象的使用方式。要工作,这必须在链接功能中,然后使用$event.target代替

link: function(scope, element, attrs) {
  scope.onClick = function($event) {
    angular.element($event.target).css('background-color', 'red');
  }
}

然后让它运行,并传递$event对象,模板,而不是

<button ng-click='onClick'>My button</button>

必须是

<button ng-click='onClick($event)'>My button</button>

将所有这些放在一起,你得到一个像

这样的指令
app.directive('coloredButton', function ColoredButtonDirective() {
  return {
    scope: {
    },
    restrict: 'E',
    template: '<button ng-click="onClick($event)">My button</button>',
    replace: true,
    link: function(scope, element, attrs) {
      scope.onClick = function($event) {
        angular.element($event.target).css('background-color', 'red');
      }
    }
  };
});

并测试如下:

describe('colored button', function() {
  var $compile, $rootScope;

  beforeEach(module('test'));

  beforeEach(inject(function(_$rootScope_, _$compile_) {
    $rootScope = _$rootScope_;
    $compile = _$compile_;
  }));

  it('should turn red when clicked', function() {
    var dom, button;
    dom = $compile(angular.element('<colored-button></colored-button>'))($rootScope);
    dom.triggerHandler('click');
    expect(dom.css('background-color')).toBe('red');
  });

});

可以在http://plnkr.co/edit/L50B59V826Z6Wm8WtgJe?p=preview

看到

但是,还有其他方法可以编写这个指令,并进行测试。

另一种方法是在链接函数中根本没有查询选择器,而是在单击时在范围上设置一些状态,然后模板使用。

app.directive('coloredButton', function ColoredButtonDirective() {
  return {
    scope: {
    },
    restrict: 'E',
    template: '<button ng-click="onClick()" ng-style="{\'background-color\': isRed ? \'red\' : \'\'}">My button</button>',
    link: function(scope, element, attrs) {
      scope.isRed = false;
      scope.onClick = function() {
        scope.isRed = true;
      }
    }
  };
});

这意味着链接功能并不依赖于DOM结构,您的一个测试可以被三个替换

  • 测试按钮点击时,调用某个范围函数
  • 测试范围函数在范围
  • 上设置某些状态
  • 测试如果范围有某种状态,则按钮是某种颜色

注意我故意删除了定义中的replace: true,原因有两个:

  • 已被弃用
  • 3个测试中的2个确实需要找到按钮,所以它更接近一个非平凡的例子

然后可以将测试本身写成

describe('colored button', function() {
  var $compile, $rootScope, dom, button, $scope;

  beforeEach(module('test'));

  beforeEach(inject(function(_$rootScope_, _$compile_) {
    $rootScope = _$rootScope_;
    $compile = _$compile_;
  }));

  beforeEach(function() {
    dom = $compile(angular.element('<colored-button></colored-button>'))($rootScope);
    button = dom.find('button');
    $scope = dom.isolateScope();
  });

  it('should call the onClick handler', function() {
    spyOn($scope, 'onClick');
    expect($scope.onClick).not.toHaveBeenCalled();
    button.triggerHandler('click');
    expect($scope.onClick).toHaveBeenCalled();
  });

  it('the onClick handler should set isRed to be true', function() {
    expect($scope.isRed).toBe(false);
    $scope.onClick();
    expect($scope.isRed).toBe(true);
  });

  it('setting isRed true should make the button red', function() {
    expect(button.css('background-color')).not.toBe('red');
    $scope.isRed = true;
    $scope.$apply();
    expect(button.css('background-color')).toBe('red');
  });
});

可以在http://plnkr.co/edit/MmZGsYLopYP876Ft6ONG?p=preview

看到

这会使你的测试更多&#34; unit-y&#34;,如果你想在单个测试中测试从点击到效果的完整流程,那么你可能不会想要实现这个目标。但是,您仍然可以将3个测试合并为1来测试它们的集成,如果这是您想要的:

it('clicking should make the button red', function() {
  expect(button.css('background-color')).not.toBe('red');
  button.triggerHandler('click');
  expect(button.css('background-color')).toBe('red');
});

可以在http://plnkr.co/edit/5WHzzzbpNFdqd94ITT8Q?p=preview

看到
相关问题