Sunday, 15 August 2010

angularjs - Function from angular js controlles is not executing when testing -



angularjs - Function from angular js controlles is not executing when testing -

i testing angularjs application jasmine , karma.

my test looks this:

describe('login test', function() { // mock our module in our tests beforeeach(module('project')); var ctrl, scope; // inject $controller , $rootscope services // in beforeeach block beforeeach(inject(function($controller, $rootscope) { // create new scope that's kid of $rootscope scope = $rootscope.$new(); // create controller ctrl = $controller('logincontroller', { $scope: scope }); })); it('should login success',function() { scope.loginclick('user', 'pass'); }); });

i have login controller loginclick function, , within function have function making post request. problem inner function never executed, seek console.log() see if function called no success. function looks this:

app.controller('logincontroller', ['$scope', '$http', '$route', function ($scope, $http, $route) { console.log('controller call'); // yes works ... $scope.loginclick = function (username, password) { console.log('controller call'); // yes works handler.reqpost('/login', userdata, function (result) { console.log('login request'); // no output sent console }); }; }]);

the handler object include in karma configuration file @ start-up.

first of all, unless have reason, $http way go in angularjs phone call back-end, makes more testable.

in case should mock post call, in unit-test don't want rely on back-end

in case, utilize spy (http://jasmine.github.io/2.0/introduction.html#section-spies):

describe('login test', function(){ beforeeach(module('project')); var ctrl, scope; beforeeach(inject(function($injector) { var $controller = $injector.get('$controller'); var $rootscope = $injector.get('$rootscope'); scope = $rootscope.$new(); ctrl = $controller('logincontroller', { $scope: scope, }); })); it('test login', function () { spyon(handler, 'reqpost'); scope.loginclick('user', 'pass'); expect(handler.reqpost).tohavebeencalledwith('user', 'pass'); }); });

angularjs jasmine karma-runner

No comments:

Post a Comment