我对测试javascript很新。我的应用程序使用angularjs。我正在使用茉莉花作为测试框架。Angularjs和Jasmine:用服务测试控制器让Ajax调用
这里是我的测试控制器:
angular.module('logonController', ["ngval", "accountFactory"])
.controller("logonController", function logOnController(accountFactory, $scope, $window) {
$scope.hasServerError = false;
$scope.Logon = function() {
accountFactory.Logon($scope.data.LogOnModel)
.then(function (data) {
$window.location.href = "/";
},
function (data) {
$scope.hasServerError = true;
});
}
})
其中accountFactory.Logon正在POST请求到服务器。 window.location.href叫
$scope.hasServerError
是到目前为止,我有设置为true-
- 在成功:
我想测试调用
accountFactory.Logon
当设法做到这一点:"use strict"; describe("Logon Controller", function() { var $scope, $location, $rootScope, $httpBackend, $controller, $window, createController; beforeEach(function() { module("logonController"); }); beforeEach(inject(function ($injector) { $rootScope = $injector.get("$rootScope"); $scope = $rootScope.$new(); $location = $injector.get("$location"); $httpBackend = $injector.get("$httpBackend"); $controller = $injector.get("$controller"); $window = $injector.get("$window"); })); beforeEach(function() { createController = function() { return $controller("logonController", { "$scope": $scope, }); }; $scope.data = { LogOnModel: { username: "user", password: "pass" } }; $window = { location: { href: jasmine.createSpy() } }; }); it("should redirect on successfull login", function() { var controller = createController(); $httpBackend.whenPOST("/Account/Logon").respond(function (method, url, data, headers) { return [200, {}, {}]; }); $scope.Logon(); $httpBackend.flush(); expect($window.location.href).toHaveBeenCalled(); }); });
我的想法是创造在$ window.location.href上检测一个间谍,并只检查它是否被调用。但我越来越
预计的间谍未知被调用。
正如我所说我很新的测试JavaScript,所以任何帮助将不胜感激。