Angular Directive Isolate Scope Unit Test Failed

2019-07-28 19:52发布

问题:

I am trying to unit test an Angular Component with Karma Jasmine for the very first time.

My index.html looks like :

<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>

And index.js looks like :

(function(angular) {
  'use strict';
    angular.module('heroApp', []).controller('MainCtrl', function MainCtrl() {
        this.hero = {
            name: 'Miles Bronson'
        };
    });
})(window.angular);

And the component heroDetail.js looks like :

(function(angular){
    'use strict';

    function HeroDetailController(){

    }

    angular.module('heroApp').component('heroDetail',{
        template:'<span>Name: {{$ctrl.hero.name}}</span>',
        controller:HeroDetailController,
        bindings:{
            hero: '='
        }
    });

})(window.angular);

Now my karma spec file looks like :

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

    });

});

But this failed. 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)

What am I doing wrong ? Please help.

UPDATE

Though this works :

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

});

回答1:

You are just missing controller reference. It should be:

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

See updated plnkr: https://plnkr.co/edit/9ZLzr4AWtCB0q43vBAdf