angularjs - Test Angular controller calls service function exactly once using Jasmine -


i have following...

app.controller('testctrl', function(testservice){    testservice.dosomething(); }); app.service('testservice', function(){    this.dosomething = function(){...}; }); 

i want use jasmine ensure dosomething called once , once. seem having trouble doing this.

also, grabbing controller compiled element this...

var element = angular.element('<my-test-directive />'); controller = view.controller('testctrl'); 

so appreciation if fits sort of formatting

update

i tried this...

describe("testing", function () {   var $rootscope,     $scope,     $compile,     testservice,     view,     $controller;   beforeeach(module("app"));   function createcontroller() {     return $controller('testctrl', {         $scope: scope,         testservice:testservice     });    }   function setupscope(_$controller_,  _$compile_, _$rootscope_, _testservice_) {     $compile = _$compile_;     $rootscope = _$rootscope_;     $scope = $rootscope.$new();     $controller = _$controller_;     testservice = _testservice_;     spyon(testservice, 'dosomething');   }   setupscope.$inject = ["$controller","$compile", "$rootscope", "testservice"];   beforeeach(inject(setupscope));   it("on intitialization, controller should register list service", function(done){     createcontroller();     scope.$digest();     expect(workorderservice.dosomething).tohavebeencalled();   }) }); 

it seems work

it better test controller in isolation , use jasmine spies this:

spyon(testservice, 'dosomething'); expect(testservice.dosomething.calls.count()).toequal(0); 

something should work in actual test.

describe('testctrl function', function() {    describe('testctrl', function() {     var $scope, testservice;      beforeeach(module('myapp'));      beforeeach(inject(function($rootscope, $controller, _testservice_) {       $scope = $rootscope.$new();       testservice = _testservice_;       spyon(testservice, 'dosomething');       $controller('mycontroller', {$scope: $scope});     }));      it('should call testservice.dosomething()', function() {       expect(testservice.dosomething.calls.count()).toequal(1);     });   }); }); 

here quick plunkr http://plnkr.co/edit/swso4y

depending on version of jasmine using might need use

expect(testservice.dosomething.calls.length).toequal(1); 

Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -