How to mock ng-grid when unit testing a controller

前端 未结 2 440
没有蜡笔的小新
没有蜡笔的小新 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: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('
    ');

    I suggest you get rid of

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

    maneuvers and use the following HTML element instead

    elm = angular.element('
    ');

    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.

提交回复
热议问题