2014-09-23 47 views
2

测试角(NG-网格)假设我有以下侦听器时与数据发射的事件:如何茉莉

$scope.$on('ngGridEventEndCellEdit', function(event, data){ 
    var entity; 

    if(data && data.targetScope && data.targetScope.row) { 
    entity = data.targetScope.row.entity; 
    } else { 
    entity = event.targetScope.row.entity; 
    } 

    entity.projectId = $scope.projectId; 

    GanttCommunicator.updateActivity(entity); 
}); 

如何测试其中事件与event.targetScope进来的情况下...?

回答

0

所以你有一个比ng-grid更高的作用域层次控制器。你想$发出一个名为ngGridEventEndCellEdit的事件来模拟ng-grid会做什么。

然后,您只需验证您希望看到的更改。你可以用茉莉花间谍来做到这一点。有关如何执行此操作的示例,请参阅下面的代码。

describe('ngGridEventEndCellEdit', function(){ 
    var scope; 
    var childScope; 
    var GanttCommunicator; 
    beforeEach(function($rootScope,$controller,GanttCommunicator){ 
    // child of $rootScope 
    scope = $rootScope.$new(); 
    // child of scope 
    childScope = scope.$new(); 
    $controller('YourControllerWithListener', { 
     $scope : scope 
    }); 
    }); 

    it('should handle an event $emitted up from a child scope', function(){ 

    scope.projectId = 12341; 
    // .and.callThrough() is jasmine2.0 syntax. jasmine 1.3 is a bit different 
    spyOn(scope,'ngGridEventEndCellEdit').and.callThrough(); 
    spyOn(GanttCommunicator,'updateActivity'); 

    var myPayload = { 
     whatsThis: 'the payload', 
     targetScope: { 
     row: { 
      entity: 'blah' 
     } 
     } 
    }; 

    // $emit only goes up, which is why we need a child scope 
    childScope.$emit('ngGridEventEndCellEdit',myPayload); 

    // See what an angular event is composed of here ... https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$on 
    var expectedEvent = {...}; 


    //expect that the spied on functions have been called with the correct values. 
    expect(scope.ngGridEventEndCellEdit).toHaveBeenCalledWith(expectedEvent,myPayload); 
    expect(GanttCommunicator.updateActivity).toHaveBeenCalledWith(jasmine.objectContaining({ 
     projectId: scope.projectId 
    })); 

    }); 
}); 
+0

谢谢你的回应杰西。但是,在我的例子中,这个有效负载进入“data”内部,从中我可以模拟data.targetScope.row.entity的值 我的问题是关于如何在我的示例中模拟以下值:event.targetScope。 row.entity 或者我可能没有完全理解你的答案? – Zoh 2014-09-25 04:39:48

+0

@Zoh,我意识到我犯了一个错误。 expect(scope.ngGridEventEndCellEdit).toHaveBeenCalledWith(expectedEvent,myPayload)是这个改变的行。在这个测试中,有效载荷/数据将贯穿您的监听器代码。我还没有测试过,但这大概是你怎么做的。 – Jesse 2014-09-25 05:14:42

0

找到了解决办法。简单的方法是模拟

var entity = { id: 1, name: 'first' }; 
var row = { entity: entity }; 
var targetScope = { row: row }; 
window.event = { 
    targetScope: targetScope 
};