我是angularjs的新手并为一个简单的控制器编写单元测试。但不知怎的,它不起作用。代码如下:
ResetPwdCtrl.js (仅提及我正在测试的功能)
function ResetPwdCtrl($scope, $modalInstance, Employee, emp){
$scope.emp= emp;
$scope.confirm = function(){
Employee.sendResetPwdLink(emp.id).success(function(){
$modalInstance.close();
}).error(function(errorObject){
$scope.alert = {
type: 'danger',
text: errorObject.statusCode
};
});
};
}]);
"员工"是一个工厂,sendResetPwdLink是一个静态方法。它的单元测试是
describe("Reset pwd", function() {
var scope, mockModalInstance, mockEmployee, emp, q, deferred, appCtrl;
beforeEach(function() {
mockEmployee = {
id : 0,
sendResetPwdLink : function(theId) {
mockEmployee.id = theId;
deferred = q.defer();
deferred.promise.success = function(fn) {
return deferred.promise.then(fn);
};
//return deferred.promise;
deferred.promise.error = function(fn) {
return deferred.promise.fail(fn);
};
return deferred.promise;
}
};
emp = {
id : 10
};
mockModalInstance = {
isClosed : false,
close : function() {
mockModalInstance.isClosed = true
}
};
});
beforeEach(inject(function($controller, $rootScope, $q) {
scope = $rootScope.$new();
q = $q;
$controller('ResetPwdCtrl', {
'$scope' : scope,
'$modalInstance' : mockModalInstance,
'Employee' : mockEmployee,
'emp' : emp
});
}));
it("confirm", function() {
scope.confirm();
deferred.resolve();
scope.$root.$digest();
expect(mockModalInstance.isClosed).toEqual(true);
});
it("confirm2", function() {
scope.confirm();
deferred.reject({errorObject:[{type: 'danger', statusCode: 401,text: statusCode}]});
scope.$root.$digest();
});
});
在运行测试时,我遇到以下错误:
重置pwd确认<<<失败! * TypeError:' undefined'不是函数(接近' ...})。错误(resetPwdCtrl.js中的函数(errorObjec ...')
重置pwd,确认2<<<失败! * TypeError:' undefined'不是函数(接近' ...})。错误(resetPwdCtrl.js中的函数(errorObjec ...')
我在网上没有得到很多帮助。请帮助!!
答案 0 :(得分:1)
describe("ResetPwdCtrl",function(){
var $rootScope,$modalInstance,ctrl;
beforeEach(module('MyApp'));
beforeEach(inject(function($injector,_Employee_,_emp_,$controller){
$rootScope=$injector.get('$rootScope');
scope=$rootScope.$new();
$modalInstance=$injector.get('$modalInstance');
ctrl=$controller(function($scope:scope){
});
}));
it('should call the confirm()',function(){
scope.confirm();
expect(scope.alert.type).toEqual('danger');
});
});
如果scope.alert.type未定义,请声明JSON对象。
希望这篇文章能为您提供帮助
答案 1 :(得分:0)
我会尝试两件事。 q
可能未定义。您可以尝试将mockEmployee定义之前的beforeEach
更改为此...
beforeEach(inject(function($q) { //ADD INJECT
q = $q //DEFINE q
mockEmployee = {...//This part looks good to me
如果这没有帮助,这就是我在测试中使用q的方式。希望它会引导你走上正确的轨道。
getData = {
get: function (id)
{
deferred = q.defer();
// Place the fake return object here
deferred.resolve(mockEmployee);
return { $promise: deferred.promise };
}
};
$rootScope.$apply();
答案 2 :(得分:0)
感谢您的回复,它对我帮助很大:)
我检查了我写作的错误情况
deferred.promise.error = function (fn) {
return deferred.promise.fail(fn);
};
相反,我添加了以下代码来检查错误情况
deferred.promise.error = function (fn) {
deferred.promise.then(null, fn);
return deferred.promise;
};
这个工作得很好!!