单元测试指令方法不存在



我正在尝试测试指令:

define(['require'], function (require){
'use strict';
var myDirective = function ($rootScope, MyService) {
    return {
        restrict: 'E',
        templateUrl: 'app/banner/banner.html',
        scope: {},
        controller: [ '$scope', '$element', function ($scope, element) {                
            $scope.sendEmail = function(data) {
                $scope.showConfirmation = false;
                $rootScope.$broadcast('process-email', data);
            };
        }]
    };
};
 return ['$rootScope', 'MyService', myDirective];
});

横幅.html

<ul>
    <li><a href="javascript:;" ng-click="sendEmail('process')" class="email-item">Send mail</a></li>
    <li><a href="javascript:;" ng-click="sendEmail('clarify')" class="email-item">Clarify mail</a></li>
</ul>

测试:

define(['require', 'angular-mocks'], function (require) {
    'use strict';
    var angular = require('angular');
    describe('MyDirective Spec ->', function () {
        var scope, $compile, element, $httpBackend;
        beforeEach(angular.mock.module('MyApp'));
        beforeEach(inject(function (_$rootScope_, _$httpBackend_) {
            scope = _$rootScope_.$new();
            $compile = _$compile_;
            $httpBackend = _$httpBackend_;
            var html = '<div my-directive></div>';
            element = $compile(angular.element(html))(scope);
            scope.$digest();
        }));
        it('should test sendEmail', function () {
            spyOn(scope, 'sendEmail').and.callThrough();
            element.find('.email-item').click();
            expect(scope.sendEmail).toHaveBeenCalled();
        });
    });
});

我收到错误:

Error: sendEmail() method does not exist

您为指令指定scope: {}的正弦,它有一个隔离的作用域。在隔离作用域上,它具有sendEmail功能。

因此,在单元测试时,为了访问该函数,您必须从指令元素中获取隔离范围,如下所示:

var isolateScope = element.isolateScope()
isolateScope.sendEmail() // <- this

如果您需要更多信息,本文可能会有所帮助:http://thejsguy.com/2015/02/12/unit-testing-angular-directives.html

最新更新