【发布时间】:2014-02-13 11:21:02
【问题描述】:
我对测试 javascript 非常陌生。我的应用程序正在使用 angularjs。我正在使用 jasmine 作为测试框架。
这是我正在测试的控制器:
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 请求。
我想测试的是当调用accountFactory.Logon:
- 成功时 - 调用 window.location.href
- 错误时
$scope.hasServerError设置为 true
到目前为止,我已经做到了:
"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 的新手,因此我们将不胜感激。
【问题讨论】:
标签: angularjs unit-testing jasmine