javascript - Jasmine angularjs - spying on a method that is called when controller is initialized -


i using jasmine karma(testacular) , web storm write unit test. having trouble spying on method gets called when controller initialized. possible spy on method called when controller initialized?

my controller code, method attempting spy on getservicesnodelist().

myapp.controller('treeviewcontroller', function ($scope, $rootscope ,$document, dataservices) {     $scope.treecollection  =  dataservices.getservicesnodelist();     $rootscope.viewportheight = ($document.height() - 100) + 'px'; }); 

and here test spec:

describe("dataservices controllers - ", function () {  beforeeach(angular.mock.module('myapp')); describe("dataservicestreeview controller - ", function () {       beforeeach(inject(function ($controller, $rootscope, $document, $httpbackend, dataservices) {         scope = $rootscope.$new(),         doc = $document,         rootscope = $rootscope;         dataservices = dataservices;          $httpbackend.when('get', '/scripts/internal/servicedata/services.json').respond(...);          var controller = $controller('treeviewcontroller', {$scope: scope, $rootscope: rootscope, $document: doc, dataservices: dataservices });          $httpbackend.flush();     }));      aftereach(inject(function($httpbackend){         $httpbackend.verifynooutstandingexpectation();         $httpbackend.verifynooutstandingrequest();     }));      it('should ensure dataservices.getservicesnodelist() called', inject(function ($httpbackend, dataservices) {         spyon(dataservices, "getservicesnodelist").andcallthrough();          $httpbackend.flush();         expect(dataservices.getservicesnodelist).tohavebeencalled();     }));   }); }); 

the test failing saying method has not been called. know should mock dataservices , pass test controller. seems still have same problem when spying on method whether mock or not. have ideas or point me resources on correct way handle this?

when writing unit tests, should isolate each piece of code. in case, need isolate service , test separately. create mock of service , pass controller.

var mockdataservices = {     getservicesnodelist: function () {         return <insert sample data here > ;     } };  beforeeach(inject(function ($controller, $rootscope, $document) {     scope = $rootscope.$new(),     doc = $document,     rootscope = $rootscope;      var controller = $controller('treeviewcontroller', {         $scope: scope,         $rootscope: rootscope,         $document: doc,         dataservices: mockdataservices     }); })); 

if service making $http request, can remove portion unit controller test. write unit test tests service making correct http calls when initialized.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -