【发布时间】:2018-01-28 06:06:41
【问题描述】:
我正在尝试测试以下组件中的方法“removePlayer”在删除播放器时是否被调用:spyOn(scope, 'removePlayer').and.callThrough();和期望(scope.removePlayer).toHaveBeenCalled();但得到以下错误:“错误::removePlayer()方法不存在 用法:spyOn(, )" 请问如何实现呢?
.component("playerList", {
templateUrl: "src/js/player/player.html",
bindings: {
list: '<'
},
controller: function() {
this.removePlayer = function(index) {
console.log('Remove player with index : ', index);
if (index > -1) {
this.list.splice(index, 1);
}
};
}
});
通过以下测试:
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
scope.list = angular.copy(playersList);
element = angular.element('<player-list list="list"></player-list>');
element = $compile(element)(scope);
scope.$apply();
}));
it('should render the text', function() {
// spyOn(scope, 'removePlayer').and.callThrough();
var title = element.find('h1');
var deleteBtn = element[0].querySelector('button');
expect(title.text()).toBe('This table contains ' + playersList.length + ' player.');
deleteBtn.click();
// expect(scope.removePlayer).toHaveBeenCalled();
expect(title.text()).toBe('This table contains ' + (playersList.length - 1) + ' player.');
});
这是模板:
<div class="container">
<h1 class- "player-table-title">This table contains {{ $ctrl.list.length }} players[![enter image description here][1]][1].</h1>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Team</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="player in $ctrl.list">
<td>{{ player.name }}</td>
<td>{{ player.position }}</td>
<td>{{ player.team }}</td>
<td>
<button type="button" class="btn btn-danger btn-sm" ng-click="$ctrl.removePlayer($index)">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
</tbody>
</table>
</div>
这是应用在浏览器中的外观:
【问题讨论】:
标签: angularjs jasmine karma-jasmine angular-components