2014-10-27 51 views
0

我正在用Jasmine和Karma测试我的angularjs应用程序。测试时未执行角度js控制的函数

我的测试是这样的:

describe('Login test', function() { 
    // Mock our module in our tests 
    beforeEach(module('Project')); 

    var ctrl, scope; 
    // inject the $controller and $rootScope services 
    // in the beforeEach block 
    beforeEach(inject(function($controller, $rootScope) { 
    // Create a new scope that's a child of the $rootScope 
    scope = $rootScope.$new(); 

    // Create the controller 
    ctrl = $controller('loginController', { 
     $scope: scope 
    }); 
    })); 

    it('should get login success',function() { 
    scope.loginClick('user', 'pass'); 
    }); 
}); 

我与loginClick功能的登录控制器,而这个函数里面我有一个正在POST请求另一个功能。问题是内部函数永远不会执行,我尝试console.log()来查看函数是否被调用,但没有成功。 我的函数如下:

app.controller('loginController', ['$scope', '$http', '$route', function ($scope, $http, $route) { 
    console.log('controller call'); // yes it works 
    ... 
    $scope.loginClick = function (username, password) { 
    console.log('controller call'); // yes it works 

    handler.reqPOST('/login', userData, function (result) { 
     console.log('login request'); // no output is sent to the console 
    }); 
}; 
}]); 

的处理对象是包括在启动的业力配置文件中

+0

如果reqPOST发出http请求,则需要使用ngMock中的$ httpBackend服务设置模拟http后端。 – Chandermani 2014-10-27 11:32:40

回答

0

首先,除非你有很好的理由,否则$http是angularJS去调用后端的方法,它也使得它更容易测试。

在任何情况下,你应该嘲笑后调用,在单元测试你不想依靠后端

在你的情况,你可以使用间谍(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'); 
    }); 
}); 
+0

'spyOn'正在创建'handler'的模拟,所以在这个例子中post调用被模拟。 – Tristan 2014-10-27 14:34:51

+0

expect(handler.reqPOST).toHaveBeenCalled(); - 这个测试通过了,但问题在于实际的POST请求从未被发送过 – 2014-10-28 07:17:44

+0

嘲笑的要点是你用一个可预测的假请求替换后端请求,参见http://en.wikipedia.org/wiki/Mock_object – Tristan 2014-10-28 08:56:01