【发布时间】:2015-07-17 22:07:43
【问题描述】:
我正在为具有角度范围函数的控制器编写单元测试,该函数在调用时调用 parse.com 框架函数,该函数调用解析服务器并返回成功参数或错误代码。
如何为单元测试模拟该对象?
控制器作用域中的函数名称是 Parse.User.logIn,这是迄今为止我为它制作的模拟对象。
mockParse = {
User: {
logIn: function(_userName, _password, callbackObj) {
callbackObj.success({
attributes:{
username: "testuser",
email: "testuser@example.com"
}
$rootScope.user = _user;
$rootScope.isLoggedIn = true;
$state.go('tab.home');
};
callbackObj.error({
err:{
code: 101
}
if (err.code == 101){
$scope.error.message = "invalid login credentials";
} else {
$scope.error.message = "Unexpected error"
}
});
}
}
}
我做对了吗?我是否必须为不同的回调响应、错误和成功创建不同的对象?
当我将它放入测试时,我在哪里注入它?我是否将它放在控制器中,像这样?:
ctrl = $controller("LoginCtrl", {
$scope: $scope,
Parse: mockParse
});
这是实际的功能:
Parse.User.logIn(($scope.user.username) , $scope.user.password, {
success: function(_user) {
console.log('Login Success');
console.log('user = ' + _user.attributes.username);
console.log('email = ' + _user.attributes.email);
$ionicLoading.hide();
$rootScope.user = _user;
$rootScope.isLoggedIn = true;
$state.go('tab.home');
},
error: function(user, err) {
$ionicLoading.hide();
// The login failed. Check error to see why.
if (err.code === 101) {
$scope.error.message = 'Invalid login credentials';
} else {
$scope.error.message = 'An unexpected error has ' +
'occurred, please try again.';
}
console.log('error message on Parse.User.logIn: ' + $scope.error.message);
$scope.$apply();
}
});
【问题讨论】:
标签: angularjs unit-testing karma-jasmine