2017-01-19 152 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); 

現在我的人緣規範文件的樣子就像:

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,但是呈現爲undefined。

這是正確的做法嗎?

+0

我覺得模板中的{{$ ctrl.hero.name}}'應該是'{{hero.name}}'這將工作正常。 –

+0

@AdnanUmer ..但這是controllerAs語法正確嗎? – StrugglingCoder

+0

沒有對等的ControllerAs在角度2 –

回答

1

我相信scope = $rootScope;應該scope = $rootScope.$new();

UPD:您也有您的安裝程序錯誤:scope.name = "Miles Bronson";應該scope.hero = { name: "Miles Bronson" };

我能夠使plunker https://plnkr.co/edit/9ZLzr4AWtCB0q43vBAdf?p=preview

工作試驗測試通過:

describe('Component:heroDetailComponent', function() { 
    var element, 
     scope; 

    beforeEach(module('plunker')); 

    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.$digest(); 
    })); 

    it('should render the text',function(){ 
     var span = element.find('span'); 
     expect(span.text()).toBe('Name: Miles Bronson') 
    }); 
}); 
+0

我也一樣。沒有運氣:( – StrugglingCoder

+0

@StrugglingCoder查看更新回答 –

+0

請問您可以提供重擊者嗎 – StrugglingCoder