我正在尝试测试指令:
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];
});
banner.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
答案 0 :(得分:2)
您已为指令指定scope: {}
,它具有独立的范围。并且它具有sendEmail
函数的隔离范围。
因此,在进行单元测试时,为了访问该函数,您必须从指令元素中获取隔离范围,如下所示:
var isolateScope = element.isolateScope()
isolateScope.sendEmail() // <- this
如果您需要更多信息,本文可能有所帮助:http://thejsguy.com/2015/02/12/unit-testing-angular-directives.html