2014-09-23 78 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 
};