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

编程入门 行业动态 更新时间:2024-10-10 15:20:01
本文介绍了角度指令隔离范围单元测试失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正尝试第一次使用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')ponent('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: plnkr.co/edit/9ZLzr4AWtCB0q43vBAdf

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

更多推荐

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

本文发布于:2023-10-10 21:58:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指令   单元测试   角度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!