角度指令隔离范围单元测试失败

时间:2017-01-20 12:33:58

标签: javascript angularjs unit-testing karma-jasmine

我试图用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)

我做错了什么?请帮助。

更新

Though this works

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

});

1 个答案:

答案 0 :(得分:2)

您只是缺少控制器参考。它应该是:

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

请参阅更新的plnkr:https://plnkr.co/edit/9ZLzr4AWtCB0q43vBAdf

相关问题