问题
How would I write a test for this following piece of code?
$scope.$on('$locationChangeSuccess', function () {
$(".modal-backdrop").removeClass('modal-backdrop');
});
回答1:
The following should work:
beforeEach(function() {
$('body').append('<div id="test" class="modal-backdrop"/>');
});
afterEach(function() {
$('#test').remove();
});
it('should remove the classname on $locationChangeSuccess', function() {
spyOn($scope, '$on').and.callThrough();
$scope.$broadcast('$locationChangeSuccess');
expect($scope.$on).toHaveBeenCalled();
expect($('#test').hasClass('modal-backdrop')).toBe(false);
});
回答2:
To trigger the handler function you need to trigger the event in the test. That can be done like this:
$scope.$broadcast('$locationChangeSuccess');
来源:https://stackoverflow.com/questions/32527074/jasmine-test-for-angularjs-locationchangesuccess