[英]Angular Directive Isolate Scope Unit Test Failed
我正在尝试第一次使用Karma Jasmine对Angular Component进行单元测试。
我的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.$new();
scope.hero = {
name:'Miles Bronson'
};
element = angular.element('<hero-detail hero="hero"></hero-detail>');
element = $compile(element)(scope);
scope.$apply();
}));
it('should render the text',function(){
expect(element.isolateScope().hero.name).toBe('Miles Bronson');
});
});
但这失败了 。 Saying :
Chrome 55.0.2883 (Windows 8.1 0.0.0) Component:heroDetailComponent should render the text FAILED
TypeError: Cannot read property 'name' of undefined
at Object.<anonymous> (test/controllers/main-controller-spec.js:38:43)
Chrome 55.0.2883 (Windows 8.1 0.0.0): Executed 2 of 2 (1 FAILED) (0 secs / 0.047Chrome 55.0.2883 (Windows 8.1 0.0.0): Executed 2 of 2 (1 FAILED) (0.763 secs / 0.047 secs)
我究竟做错了什么 ? 请帮忙。
UPDATE
Though this works
:
it('should render the text',function(){
var span = element.find('span');
expect(span.text()).toBe('Name: Miles Bronson');
});
您只是缺少控制器参考。 它应该是:
element.isolateScope().$ctrl.hero.name
查看更新的plnkr: https ://plnkr.co/edit/9ZLzr4AWtCB0q43vBAdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.