我试图用Karma + Jasmine测试AngularJS自定义指令。我找到了一种方法来检查网络上的许多参考文献。但解决方案似乎并不是正确的方法。我们先来看一个例子,这是test.js:
angular.module("app", [])
.directive("test", function() {
return {
restrict: 'E',
scope: {
defined: '='
},
templateFile: "test.html",
controller: function($scope) {
$scope.isDefined = function() {
return $scope.defined;
};
}
};
});
describe("Test directive", function() {
var elm, scope;
beforeEach(module("app"));
beforeEach(module("test.html"));
beforeEach(inject(function($rootScope, $compile, $injector) {
elm = angular.element("<test defined='defined'></test>");
scope = $rootScope;
scope.defined = false;
$compile(elm)(scope);
scope.$digest();
}));
it("should not be initially defined", function() {
expect(elm.scope().$$childTail.isDefined()).toBe(false);
});
});
现在指令模板文件test.html:
<button data-ng-click='defined = true'></button>
最后是karma.conf.js:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'angular.min.js',
'angular-mocks.js',
'test.js',
'test.html'
],
exclude: [],
preprocessors: {
"test.html": ['ng-html2js']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Firefox'],
singleRun: true
});
};
我使用以下命令行运行测试:
karma start karma.conf.js
对我来说似乎很奇怪的是,控制器中定义的范围函数只能通过$$childTail
属性访问。如果我尝试直接从元素的范围中调用它,我得到一个未定义的值elm.scope().isDefined()
。有人有更好的解决方案吗?
谢谢!
答案 0 :(得分:6)
因为您的指令使用隔离范围,而不是
elm.scope()
你应该可以使用
elm.isolateScope()
http://docs.angularjs.org/api/ng/function/angular.element
解释(简要)函数isolateScope