【问题标题】:unit testing angularjs directive单元测试 angularjs 指令
【发布时间】:2013-04-16 07:09:59
【问题描述】:

我想开始为我的 angularjs 项目进行单元测试。这远非直截了当,我觉得这真的很难。我正在使用业力和茉莉花。对于测试我的路线和应用程序依赖项,我很好。但是你会如何测试这样的指令呢?

angular.module('person.directives', []).
directive("person", function() {
return {
    restrict: "E",
    templateUrl: "person/views/person.html",
    replace: true,
    scope: {
        myPerson: '='
    },
    link: function (scope, element, attrs) {

    }        
}

});

例如,我将如何测试是否找到了模板?

【问题讨论】:

标签: angularjs karma-runner


【解决方案1】:

这是要走的路https://github.com/vojtajina/ng-directive-testing

基本上,您使用beforeEach 创建编译公开一个元素及其作用域,然后模拟作用域变化和事件处理程序并查看代码是否适当地做出反应并更新元素和范围。这是一个非常简单的例子。

假设:

scope: {
  myPerson: '='
},
link: function(scope, element, attr) {
  element.bind('click', function() {console.log('testes');
    scope.$apply('myPerson = "clicked"');
  });
}        

我们希望当用户单击带有指令的元素时,myPerson 属性变为clicked。这是我们需要测试的行为。所以我们将编译后的指令(绑定到一个元素)暴露给所有规范:

var elm, $scope;

beforeEach(module('myModule'));

beforeEach(inject(function($rootScope, $compile) {
  $scope = $rootScope.$new();
  elm = angular.element('<div t my-person="outsideModel"></div>');
  $compile(elm)($scope);
}));

那么你就断言:

it('should say hallo to the World', function() {
  expect($scope.outsideModel).toBeUndefined(); // scope starts undefined
  elm.click(); // but on click
  expect($scope.outsideModel).toBe('clicked'); // it become clicked
});

Plnker here。你需要 jQuery 来做这个测试,来模拟click()

【讨论】:

  • 对于模板 html,用于动态加载到 $templateCache。您可以只使用 html2js 业力预处理器,这归结为将模板 '.html' 添加到 conf.js 文件中的文件以及 preprocessors = { '.html': 'html2js' };并将 html 指定为 js 测试文件中的模块
猜你喜欢
  • 2014-08-06
  • 1970-01-01
  • 2014-05-23
  • 2015-09-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 2015-07-29
  • 2015-11-15
相关资源
最近更新 更多