AngularJS, prevent init method on controller from launching during jasmine tests

孤街醉人 提交于 2019-12-04 02:44:47
pkozlowski.opensource

It is a bit hard to provide precise guidance without seeing a live code example (this is why it is usually a good idea to provide a plunk that has a template for Jasmine tests) but it sounds like your init method executes some setup logic that should be different depending on the environment. If so the way to move forward would be to encapsulate this initialization logic into a dedicated service and mock this service during testing (this is exactly what @Joe Dyndale is suggesting).

Provided that your controller looks like follows:

app.controller('MainCtrl', function($scope) {
  $scope.init = function() {
    //something I really don't want to call during test
    console.log("I'm executing");
  };
});

It could be refactored to:

app.factory('InitService', function() {
  return {
    init = function() {
      //something I really don't want to call during test
      console.log("I'm executing");
    }
  };
});

app.controller('MainCtrl', function($scope, InitService) {
  InitService.init();
});

and then the test with mocking could look like so:

describe('Testing an initializing controller', function() {
  var $scope, ctrl;

  //you need to indicate your module in a test
  beforeEach(module('plunker'));
  beforeEach(module(function($provide){
    $provide.factory('InitService', function() {
      return {
        init: angular.noop
      };
    });
  }));
  beforeEach(inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();
    ctrl = $controller('MainCtrl', {
      $scope: $scope
    });
  }));

  it('should test sth on a controller', function() {
    //
  });
});

Finally here is a live code in plunker

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