How to mock ng-grid when unit testing a controller

夙愿已清 提交于 2019-12-03 08:37:40

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!