How to mock ng-grid when unit testing a controller

前端 未结 2 439
没有蜡笔的小新
没有蜡笔的小新 2021-02-10 14:30

I\'m currently trying to write tests for existing blocks of code and running into an issue with a controller that has a nested ng-grid inside of it. The issue comes from the con

相关标签:
2条回答
  • 2021-02-10 15:03

    Your (major!) problem here is that the controller is making assumptions about a View. It should not know about and thus not interact with ng-grid. Controllers should be View-independent! That quality (and Dependency Injection) is what makes controllers highly testable. The controller should only change the ViewModel (i.e. its $scope), and in testing you validate that the ViewModel is correct.

    Doing otherwise goes against the MVVM paradigm and best practices.

    If you feel like you must access the View (i.e. directives, DOM elements, etc...) from the controller, you are likely doing something wrong.

    0 讨论(0)
  • 2021-02-10 15:14

    The problem in the second Failing test is gridOptions and myData is not defined prior to the compilation. Notice the sequence of the 2 statements.

    Passing oCtrl = $controller('MainCtrl', { $scope: $scope }); $compile(elm)($scope);

    Failing

    $compile(elm)($scope);
    oCtrl = $controller('MainCtrl', { $scope: $scope });
    

    In both cases you are trying to use the same html

    elm = angular.element('<div ng-grid="gridOptions" style="width: 1000px; height: 1000px"></div>');
    

    I suggest you get rid of

    oCtrl = $controller('MainCtrl', { $scope: $scope });
    

    maneuvers and use the following HTML element instead

    elm = angular.element('<div ng-controller="MainCtrl" 
          ng-grid="gridOptions" style="width: 1000px; height: 1000px"></div>');
    

    Notice ng-controller="MainCtrl".

    So the end story is that you need gridOptions defined somewhere so that it ngGrid can access it. And make sure gridOptions dependent code in controller is deferred in a $timeout.

    Also take a look at the slight changes in app.js

    $timeout(function(){
        //your gridOptions dependent code
        $scope.gridOptions.$gridScope.columns.each(function(){
          return;
        });  
      });
    

    Here is the working plnkr.

    0 讨论(0)
提交回复
热议问题