使用Jasmine进行AngularJS测试:检查$window.off()

AngularJS testing with Jasmine: Check $window.off()

本文关键字:window off 检查 Jasmine 进行 AngularJS 测试 使用      更新时间:2023-09-26

如何检查$window.off()是否在$scope.$destroy()上被调用。$window是angular.element。

代码示例:

...
$scope.$on('$destroy', function(){
    $window.off('event name');
});
...

测试示例:

it('should unbind all events from $window object', function () {
    spyOn($window, 'off').and.callThrough();
    $scope.$destroy();
    expect($window.off).toHaveBeenCalled();
});

结果:Error: Expected spy off已被调用。有什么建议吗?谢谢!

试试这个

var rootScope ;
beforeEach(inject(function($rootScope))){
    rootScope = $rootScope;
}

it('should unbind all events from $window object', function () {
    spyOn($window, 'off').and.callThrough();
    $rootScope.$broadcast("$destroy", args);
    expect($window.off).toHaveBeenCalled();
});

这实际上是一个jQuery函数,所以您需要将spy应用到初始化jQuery的任何地方。$window可以保留,因为它是附加函数的元素,例如:

it('should unbind all events from $window object', function () {
    spyOn(angular.element.prototype, 'off').and.callThrough();
    $rootScope.$broadcast('$destroy', args);
    expect($window.off).toHaveBeenCalled();
});

我可能应该补充一些jQuery库添加了一大堆自己的事件监听器,在这种情况下,你想确保你得到最近的事件后,你初始化和添加自己的:

expect($el.off.calls.mostRecent().args).toContain('click', jasmine.any(Function));