gpt4 book ai didi

javascript - Angular Directive(指令)隔离范围单元测试失败

转载 作者:行者123 更新时间:2023-11-30 15:34:32 26 4
gpt4 key购买 nike

我第一次尝试使用 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);

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

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

});

});

但这失败了说:

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)

我做错了什么?请帮忙。

更新

虽然这有效:

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

});

最佳答案

您只是缺少 Controller 引用。应该是:

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

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

关于javascript - Angular Directive(指令)隔离范围单元测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41763818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com