【问题标题】:Angular Directive Isolate Scope Unit Test FailedAngular 指令隔离范围单元测试失败
【发布时间】:2017-01-20 12:33:57
【问题描述】:

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

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

});

【问题讨论】:

    标签: javascript angularjs unit-testing karma-jasmine


    【解决方案1】:

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

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

    查看更新的 plnkr:https://plnkr.co/edit/9ZLzr4AWtCB0q43vBAdf

    【讨论】:

    • 救世主。你是男人。但只是一个愚蠢的问题。在描述块中没有$ctrl 的引用。那么它从哪里获得使用的参考呢?它不应该只适用于hero.name,因为这是该块中唯一的东西吗?
    • 好吧,我想如果你的hero-detail 是一个纯指令,但它是一个带有控制器的组件。因此,数据存储在控制器命名空间中看起来是合乎逻辑的。但是我对角度组件没有太多经验,所以我无法真正说出它们是如何深入工作的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 2015-02-26
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 2013-06-26
    • 2014-12-13
    相关资源
    最近更新 更多