我有一个想要进行单元测试的指令,但是我遇到了无法访问我的独立作用域的问题。下面是指令:
<my-directive></my-directive>
以及它背后的代码:
angular.module('demoApp.directives').directive('myDirective', function($log) {
return {
restrict: 'E',
templateUrl: 'views/directives/my-directive.html',
scope: {},
link: function($scope, iElement, iAttrs) {
$scope.save = function() {
$log.log('Save data');
};
}
};
});
下面是我的单元测试:
describe('Directive: myDirective', function() {
var $compile, $scope, $log;
beforeEach(function() {
// Load template using a Karma preprocessor (http://tylerhenkel.com/how-to-test-directives-that-use-templateurl/)
module('views/directives/my-directive.html');
module('demoApp.directives');
inject(function(_$compile_, _$rootScope_, _$log_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
$log = _$log_;
spyOn($log, 'log');
});
});
it('should work', function() {
var el = $compile('<my-directive></my-directive>')($scope);
console.log('Isolated scope:', el.isolateScope());
el.isolateScope().save();
expect($log.log).toHaveBeenCalled();
});
});
但是当我打印出隔离的作用域时,结果是undefined
。但真正让我困惑的是,如果我在指令中简单地使用template
而不是templateUrl
,那么一切都会正常工作:isolateScope()
有一个完全scope
的对象作为其返回值,一切都很好。然而,不知何故,当使用templateUrl
时,它就崩溃了。这是ng-mocks
中的错误还是Karma预处理器中的错误?
提前谢谢。
发布于 2014-04-30 04:37:42
我也有同样的问题。似乎在结合使用templateUrl
调用$compile(element)($scope)
时,摘要周期不会自动启动。因此,您需要手动将其关闭:
it('should work', function() {
var el = $compile('<my-directive></my-directive>')($scope);
$scope.$digest(); // Ensure changes are propagated
console.log('Isolated scope:', el.isolateScope());
el.isolateScope().save();
expect($log.log).toHaveBeenCalled();
});
我不确定为什么$compile
函数不能为您做这件事,但这一定是templateUrl
工作方式的一些特殊之处,因为如果您使用内联模板,就不需要调用$scope.$digest()
。
发布于 2015-09-09 21:43:16
在Angularjs 1.3中,如果您在应用程序配置中禁用debugInfoEnabled
:
$compileProvider.debugInfoEnabled(false);
isolateScope()
也返回undefined
!
发布于 2015-02-13 02:44:57
在定义isolateScope()
之前,我必须模拟和刷新$httpBackend
。请注意,$scope.$digest()
并没有起到什么作用。
指令:
app.directive('deliverableList', function () {
return {
templateUrl: 'app/directives/deliverable-list-directive.tpl.html',
controller: 'deliverableListDirectiveController',
restrict = 'E',
scope = {
deliverables: '=',
label: '@'
}
}
})
测试:
it('should be defined', inject(function ($rootScope, $compile, $httpBackend) {
var scope = $rootScope.$new();
$httpBackend.expectGET('app/directives/deliverable-list-directive.tpl.html').respond();
var $element = $compile('<deliverable-list label="test" deliverables="[{id: 123}]"></deliverable-list>')(scope);
$httpBackend.flush();
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
expect($element).toBeDefined();
expect($element.controller).toBeDefined();
scope = $element.isolateScope();
expect(scope).toBeDefined();
expect(scope.label).toEqual('test');
expect(scope.deliverables instanceof Array).toEqual(true);
expect(scope.deliverables.length).toEqual(1);
expect(scope.deliverables[0]).toEqual({id: 123});
}));
我使用的是Angular 1.3。
https://stackoverflow.com/questions/21578762
复制相似问题