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

What is the idiomatic way to test an AngularJS directive?

本文关键字:方法 是什么 AngularJS 指令 测试      更新时间:2023-09-26

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

例如,假设我有一个指令,其中包含一个按钮,单击该按钮时会改变颜色,那么以下内容对于 DOM 集成测试是否是惯用语?

彩色按钮指令规范.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');
    });
});

彩色按钮.html

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

彩色按钮指令.js

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

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

// 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('$compile'(;//我可以注射$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 是一个没有querySelector方法的jQlite对象
  • 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

这将使您的测试更加"单元y",如果您想在单个测试中测试从点击到效果的完整流程,这当然不是您想要实现的。但是,如果您愿意,您仍然可以将 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 看到