【发布时间】:2017-01-19 12:52:14
【问题描述】:
我第一次尝试使用 Karma Jasmine 对 Angular 组件进行单元测试。
我的index.html 看起来像:
<body ng-app="heroApp">
<!-- components match only elements -->
<div ng-controller="MainCtrl as ctrl">
<b>Hero</b><br>
<hero-detail hero="ctrl.hero"></hero-detail>
</div>
</body>
</html>
index.js 看起来像:
(function(angular) {
'use strict';
angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
this.hero = {
name: 'Miles Bronson'
};
});
})(window.angular);
组件 heroDetail.js 看起来像:
(function(angular){
'use strict';
function HeroDetailController(){
}
angular.module('heroApp').component('heroDetail',{
template:'<span>Name: {{$ctrl.hero.name}}</span>',
controller:HeroDetailController,
bindings:{
hero: '='
}
});
})(window.angular);
现在我的业力规范文件看起来像:
describe('Component:heroDetailComponent',function(){
beforeEach(function(){
module('heroApp');
});
var element,
scope;
beforeEach(inject(function($rootScope,$compile){
scope = $rootScope;
scope.name = "Miles Bronson";
element = angular.element('<hero-detail hero="name"></hero-detail>');
element = $compile(element)(scope);
scope.$apply();
}));
it('should render the text',function(){
var span = element.find('span');
expect(span.text()).toBe('Name: Miles Bronson')
});
});
但这失败了。 Saying :
Chrome 55.0.2883 (Windows 8.1 0.0.0) Component:heroDetailComponent should render the text FAILED
Expected 'Name: ' to be 'Name: Miles Bronson'.
at Object.<anonymous> (test/controllers/main-controller-spec.js:35:29)
Chrome 55.0.2883 (Windows 8.1 0.0.0): Executed 2 of 2 (1 FAILED) (0.065 secs / 0.058 secs)
我做错了什么?请帮忙。我也尝试了element.isolateScope().name 但呈现未定义。。
正确的做法是什么?
【问题讨论】:
-
我认为模板中的
{{$ctrl.hero.name}}应该是{{hero.name}},这样可以正常工作。 -
@AdnanUmer .. 但这是 controllerAs 的语法对吗?
-
角度 2 中没有 ControllerAs 的等价物
-
@AdnanUmer 很抱歉没有指出这一点。我在 Angular 1.5
标签: angularjs karma-runner karma-jasmine