2014-10-27 52 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