【问题标题】:How to test on destroy scope如何测试销毁范围
【发布时间】:2013-09-27 11:08:32
【问题描述】:

如何在 angularjs 中对指令的 $destroy 事件进行单元测试?

我的指令中有代码:

scope.$on('$destroy', function () {
    //clean something
});

我的测试代码:

it('on destroy',function(){
    scope.$destroy();
    scope.$digest();

    //expect everything done?
});

任何建议!

【问题讨论】:

    标签: javascript unit-testing angularjs jasmine


    【解决方案1】:

    您应该测试在$destroy 事件中执行的代码。这是一个使用控制器的人为示例:

    测试

    it('sets destroyed to true when the scope is destroyed', function() {
      // Arrange
      $scope.destroyed = false;
    
      // Act
      $scope.$destroy();
    
      // Assert
      expect($scope.destroyed).toBe(true);
    });
    

    控制器

    app.controller('MainCtrl', function($scope) {
      $scope.$on('$destroy', function() {
        $scope.destroyed = true;
      });
    });
    

    Plunkerhere.

    【讨论】:

    • 嗨迈克尔!我认为您对控制器范围的解决方案。我想在指令中测试 $destroy 范围。谢谢!
    • 我认为这与指令的解决方案相同。你能用你的代码创建一个 Plunker 脚本吗?
    • 这个很实用。我很好奇是否有任何内置的布尔标志来检查状态。换句话说,AngularJS 本身只会通过检查特定的布尔标志来破坏作用域一次?
    【解决方案2】:

    您可以从指令的模板中选择 DOM 并获取它的范围,然后运行 ​​$destroy()。

    例如:

    你的 tpl:

    "<div id='tuna'></div>"
    

    你的测试:

    it('test on destroy', function(){
      var isolateScope = $(element).find('#tuna').eq(0).scope();
      isolateScope.$destroy();
    })
    

    希望能帮到你!

    【讨论】:

      【解决方案3】:

      Angular 的isolateScope 比使用jQuery 更可取。您可能已经像这样在测试上方的 beforeEach 中编译了元素:

      myEl = '<div my-el>MY EL</div>';
      scope = $rootScope.$new();
      directiveElement = $compile(myEl)(scope);
      scope.$digest();
      

      现在在您的测试中,您可以访问isolateScope 并致电$destroy

      var isolated = directiveElement.isolateScope();
      isolated.$destroy();
      

      【讨论】:

        【解决方案4】:

        这是我的工作:

        var destroyed = spyOn(scope, '$destroy').and.callThrough();
        scope.$destroy();
        expect(destroyed).toHaveBeenCalled();
        

        与其他答案不同,我不必创建仅对测试有意义的 flag 变量,而且,使用 Jasmine spyOn 和 callThrough 来检查函数是否 $destry 对我来说更有意义正在成功调用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多