1
我想單元測試一個角度組件與Karma茉莉花第一次。角度指令隔離作用域單元測試失敗
我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');
});
救主。你是男人。但只是一個愚蠢的問題。在描述塊中沒有引用'$ ctrl'。那麼它在哪裏得到參考?它不應該只與'hero.name'一起工作,因爲那是該塊中唯一的東西? – StrugglingCoder
好吧,我猜如果你的'hero-detail'是一個純粹的指令,但它是一個帶有控制器的組件。所以數據存儲在控制器名稱空間中看起來很合理。但是我沒有太多關於角度組件的經驗,所以我不能真正知道他們是如何深入研究的 –