fae*_*ons 5 javascript unit-testing jasmine angularjs-directive karma-runner
我正在尝试使用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);
});
});
Run Code Online (Sandbox Code Playgroud)
现在指令模板文件test.html:
<button data-ng-click='defined = true'></button>
Run Code Online (Sandbox Code Playgroud)
最后是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
});
};
Run Code Online (Sandbox Code Playgroud)
我使用以下命令行运行测试:
karma start karma.conf.js
Run Code Online (Sandbox Code Playgroud)
对我来说似乎很奇怪的是控制器中定义的范围函数只能由$$childTail
属性访问.如果我尝试直接从元素的作用域调用它,我得到一个未定义的值elm.scope().isDefined()
.有人有更好的解决方案吗?
谢谢!
因为您的指令使用隔离的范围,而不是
elm.scope()
Run Code Online (Sandbox Code Playgroud)
你应该可以使用
elm.isolateScope()
Run Code Online (Sandbox Code Playgroud)
该函数isolateScope
在http://docs.angularjs.org/api/ng/function/angular.element上进行了简要解释
归档时间: |
|
查看次数: |
4663 次 |
最近记录: |