角度/茉莉花单元测试 - 如果在测试函数中清除其$ scope元素,如何测试函数?

时间:2016-09-24 16:51:43

标签: angularjs jasmine karma-jasmine

我有一个看起来像的控制器功能:

$scope.clearMarkers = function(){
    for(var i = 0; i < $scope.markers.length; i++){
        $scope.markers[i].setMap(null);
    }
    $scope.markers = [];
};

我对上述内容的单元测试如下:

describe('clearMarkers Test', function(){
    it('should call the setMap() method on each array object inside of scope.markers and then set scope.markers to an' +
       'empty array', function(){
        scope.markers = [{
            setMap: jasmine.createSpy('scope.markers[0]#setMap')
        }, {
            setMap: jasmine.createSpy('scope.markers[1]#setMap')
        }, {
            setMap: jasmine.createSpy('scope.markers[2]#setMap')
        }];
        scope.clearMarkers();
        expect(scope.markers[0].setMap).toHaveBeenCalledWith(null);
        expect(scope.markers[1].setMap).toHaveBeenCalledWith(null);
        expect(scope.markers[2].setMap).toHaveBeenCalledWith(null);
        expect(scope.markers).toEqual([]);
    });
});

在断言应该调用setMap()方法时,上述测试会出错,因为在$scope.markers = []中设置$scope.clearMarkers()也会删除我创建的间谍。

如果我在$scope.markers = []中注释掉$scope.clearMarkers(),那么我的setMap()断言会按预期工作。

在这种情况下,我如何保护我的间谍?

2 个答案:

答案 0 :(得分:0)

Spies应该是调用时的对象方法,但它们不需要是要声明的对象方法:

var markerSpy1 = jasmine.createSpy();
...

scope.markers = [
  { setMap: markerSpy1 },
  ...
];

scope.clearMarkers();
expect(markerSpy1).toHaveBeenCalledWith(null);
...
expect(scope.markers).toEqual([]);

答案 1 :(得分:0)

你可以这样做,在实际功能上创建间谍并检查它们是否被调用,

describe('clearMarkers Test', function(){
it('should call the setMap() method on each array object inside of scope.markers and then set scope.markers to an' +
   'empty array', function(){

   spyOn(scope.markers[0], 'setMap')// setting spy on this function
   spyOn(scope.markers[1], 'setMap')
   spyOn(scope.markers[2], 'setMap')
    scope.markers = [{
        setMap: jasmine.createSpy('scope.markers[0]#setMap')
    }, {
        setMap: jasmine.createSpy('scope.markers[1]#setMap')
    }, {
        setMap: jasmine.createSpy('scope.markers[2]#setMap')
    }];
    scope.clearMarkers();
    expect(scope.markers[0].setMap).toHaveBeenCalledWith(null);
    expect(scope.markers[1].setMap).toHaveBeenCalledWith(null);
    expect(scope.markers[2].setMap).toHaveBeenCalledWith(null);
    expect(scope.markers).toEqual([]);
});

});

如果你想调用间谍功能,只需使用:

spyOn(scope.markers[0], 'setMap').and.callThrough()

希望这能解决您的问题