如何对角度指令进行单元测试

Jea*_*eri 8 javascript unit-testing angularjs

单元测试角度指令并不是很难,但我发现有不同的方法可以做到这一点.

出于本文的目的,我们假设以下指令

angular.module('myApp')
    .directive('barFoo', function () {
        return {
            restrict: 'E',
            scope: true,
            template: '<p ng-click="toggle()"><span ng-hide="active">Bar Foo</span></p>',
            controller: function ($element, $scope) {
                this.toggle() {
                    this.active = !this.active;
                }
            }
        };
    });
Run Code Online (Sandbox Code Playgroud)

现在我可以想出两种单元测试方法

方法1:

describe('Directive: barFoo', function () {
    ...
    beforeEach(inject(function($rootScope, barFooDirective) {
        element = angular.element('<bar-foo></bar-foo>');
        scope = $rootScope.$new();
        controller = new barFooDirective[0].controller(element, scope);
    }));

    it('should be visible when toggled', function () {
        controller.toggle();
        expect(controller.active).toBeTruthy();
    });
});
Run Code Online (Sandbox Code Playgroud)

方法2:

beforeEach(inject(function ($compile, $rootScope) {
    element = angular.element('<bar-foo></bar-foo>');
    scope = $rootScope.$new();
    $compile(element)(scope);
    scope.$digest();
}));

it ('should be visible when toggled', function () {
    element.click();
    expect(element.find('span')).not.toHaveClass('ng-hide');
});
Run Code Online (Sandbox Code Playgroud)

所以,我很好奇这两种方法的优点和缺点是哪一种最强大?

des*_*cne 1

我喜欢做的是创建我的测试故事,就像这个虚拟示例一样。

'use strict';

describe('app controller', function() {

  var scope;

  ...   

  beforeEach(angular.mock.module('MyModule'));

  it('should have properties defined', function() {

    expect(scope.user).toEqual(user);
    ...    

  });

  it('should have getFaqUrl method', function() {

    expect(scope.getFaqUrl).toEqual(refdataService.getFaqUrl);

  });

  it('should signout and delete user data from local storage', function() {

    ...

  });

});
Run Code Online (Sandbox Code Playgroud)

所以我猜你只是没有在第二个例子中说明它,但如果你这样做了,在测试时总是使用描述外壳,只是一个很好的做法。

至于测试本身,我建议避免使用显式调用scope.$digest()的方法,特别是因为它对于测试的目的似乎没有必要。

很快,我会选择方法 1。