【问题标题】:Jasmine test for AngularJS $locationChangeSuccessAngularJS $locationChangeSuccess 的 Jasmine 测试
【发布时间】:2015-09-11 15:30:53
【问题描述】:

我将如何为以下这段代码编写测试?

        $scope.$on('$locationChangeSuccess', function () {
            $(".modal-backdrop").removeClass('modal-backdrop');
        });

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    以下应该有效:

    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】:

      要触发处理函数,您需要在测试中触发事件。可以这样做:

      $scope.$broadcast('$locationChangeSuccess');
      

      【讨论】:

      • 谢谢,感谢您的提示。我想我也在问我如何为此编写一个合法的测试?
      猜你喜欢
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 2013-08-29
      • 2014-05-04
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多