2017-01-20 9 views
1

カルマジャスミンでアンギュラングユニットのユニットテストを初めて試みました。角度指令孤立スコープユニットテストに失敗しました

のように私の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); 

私のカルマspecファイルを見て今以下のようなS:

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'); 

}); 

答えて

2

あなたは、コントローラの参照が欠落しています。それは次のようになります。https://plnkr.co/edit/9ZLzr4AWtCB0q43vBAdf

+0

救い主:

element.isolateScope().$ctrl.hero.name 

が更新plnkrを参照してください。あなたは男です。しかし、ただのばかげた質問です。記述ブロックには '$ ctrl'の参照はありません。だからどこで参考になるのですか?それはブロック内の唯一のものなので、 'hero.name'と一緒に使うべきではありませんか? – StrugglingCoder

+0

まあ、あなたの 'hero-detail'が純粋なディレクティブだと思っていますが、それはコントローラを備えたコンポーネントです。したがって、データはコントローラの名前空間に格納されているように見えます。しかし、私は角度のある部品で多くの経験を持っていないので、彼らはどのように深く働いているのかは分かりません –

関連する問題