我有 Controller 代码:
$scope.$on('load', function (event) {
$scope.getData();
event.stopPropagation();
});
和测试代码:
it('$on load', function(event) {
var controller=createController();
spyOn(scope, '$on').andCallThrough();// I have also tried to spy scope getData
scope.$broadcast('load');
expect(scope.$on).toHaveBeenCalledwith("load");
});
类型错误:event.stopPropagation 不是函数
如何定义单元测试调用中的参数?
最佳答案
换个方式思考...
如果您在作用域上触发 load 事件,那么您预计 getData 已被调用...
在 getData 上放置一个 spy ,然后您就可以预期该函数已被调用。
我测试此类事情的方法是将 spy 放置在 $broadcast 上。
spyOn($scope, '$broadcast').and.callThrough();
spyOn(event, 'preventDefault').and.callFake(function() {});
然后在描述 block 中
describe('load event', function() {
it('should call getData method', function() {
$scope.$broadcast('load');
expect($scope.getData).toHaveBeenCalled();
});
});
关于javascript - 如何在 Karma 中使用参数测试 $on 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136784/