Sunday, 15 June 2014

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



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

i have controller init() method launched on instantiation. bunch of things useful app in live environment, messes unit-tests spies.

is there way prevent phone call when instantiating controller in unit-test environment ? or maybe way have called automatically in webapp context without making explicit phone call init() @ end of controller code ?

it bit hard provide precise guidance without seeing live code illustration (this why thought provide plunk has template jasmine tests) sounds init method executes setup logic should different depending on environment. if way move forwards encapsulate initialization logic dedicated service , mock service during testing (this @joe dyndale suggesting).

provided controller looks follows:

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

it refactored to:

app.factory('initservice', function() { homecoming { init = function() { //something don't want phone call during test console.log("i'm executing"); } }; }); app.controller('mainctrl', function($scope, initservice) { initservice.init(); });

and test mocking so:

describe('testing initializing controller', function() { var $scope, ctrl; //you need indicate module in test beforeeach(module('plunker')); beforeeach(module(function($provide){ $provide.factory('initservice', function() { homecoming { init: angular.noop }; }); })); beforeeach(inject(function($rootscope, $controller) { $scope = $rootscope.$new(); ctrl = $controller('mainctrl', { $scope: $scope }); })); it('should test sth on controller', function() { // }); });

finally here live code in plunker: http://plnkr.co/edit/fgzmjnfpqeklt0ieva7d?p=preview

initialization angularjs jasmine

No comments:

Post a Comment