AngularJS, prevent the init method from running on the controller during jasmine tests

I have a controller with the init () method launched when instantiating. It does a ton of things that are useful for my application in a live environment, but it's a mess with my spyware modules.

Is there a way to prevent it from being called when creating a controller instance in a single test environment? Or maybe a way to automatically call it in the webapp context without explicitly calling init () at the end of the controller code?

+8
angularjs initialization jasmine
source share
1 answer

It’s a little difficult to provide an accurate guide without seeing an example of live code (therefore, it is usually recommended to create a bar with a template for Jasmine tests), but it looks like your init method executes some installation logic, which should differ depending on the environment. If so, then moving forward would be to encapsulate this initialization logic in a dedicated service and make fun of this service during testing (this is exactly what @Joe Dyndale offers).

Assuming your controller looks like this:

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

It can be reorganized into:

 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 a mock test might look like this:

 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 the living code in the plunker

+12
source share

All Articles