角度指令隔离范围单元测试失败 [英] Angular Directive Isolate Scope Unit Test Failed

查看:95
本文介绍了角度指令隔离范围单元测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试第一次使用Karma Jasmine对Angular组件进行单元测试.

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

我的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);

现在我的业力规范文件看起来像:

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

    });

});

但这失败. 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');

});

推荐答案

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

You are just missing controller reference. It should be:

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

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

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

这篇关于角度指令隔离范围单元测试失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆