【发布时间】:2015-12-09 22:34:12
【问题描述】:
我正在尝试为我的表单处理控制器设置一个单元测试,但我似乎在正确设置它时遇到了问题。
这是我的控制器处理表单的代码:
app.controller("FormController", ['$scope', '$http', '$window', function($scope, $http, $window) {
$scope.message = "";
$scope.processForm = function() {
$scope.message = "Processing form";
$scope.messageStyle = {
"color": "green"
};
$http({
method: 'POST',
url: '/register',
data:{
"username": $scope.user.username,
"email": $scope.user.email,
"password": $scope.user.password,
"confirm": $scope.user.confirm
}
}).success(function(data) {
$scope.message = data.msg;
if (data.success) {
$window.location.href = "/confirm";
} else {
$scope.messageStyle = {
"color": "red"
};
}
});
};
}]);
这是我使用 Mocha 和 Chai 的单元测试代码:
describe("FormController", function(){
var scope;
var ctrl;
var httpBackend;
var http;
beforeEach(module("home"));
beforeEach(inject(function($rootScope, $controller, $httpBackend, $http) {
scope = $rootScope.$new();
http = $http;
ctrl = $controller("FormController", {$scope : scope, $http : http});
httpBackend = $httpBackend;
}));
describe("when calling the processForm function", function(){
beforeEach(function() {
scope.processForm();
});
it("Should contain a message", function(){
expect(scope.message).to.equal("Processing form");
});
});
});
当我运行测试时,我得到以下错误:TypeError: 'undefined' is not an object (evaluating '$scope.user.username')
我应该如何解决这个问题?
【问题讨论】:
-
为什么要对 POST 数据进行字符串化并添加内容类型标头? Angular 的
$http为您完成所有这些工作 -
另外,你显然需要在调用
processForm之前在你的作用域上创建一个user对象 -
@Phil 我已更新我的代码以反映 POST 数据更改。我的
user来自 ng-model。所以我在 html 表单中有类似ng-model="user.username"的东西。 -
控制器测试不包含任何模板,因此您必须在调用
processForm()之前手动设置模型数据 -
在测试中调用
scope.processForm()之前,请添加scope.user = {username: 'foo', email: 'foo@example.com', ...}。当然,您还必须将预期的 HTTP 调用添加到httpBackend
标签: javascript angularjs unit-testing mocha.js chai