我的控制器的初始化:
var init = function () {
httpUsers.getUsers().then(function (data) {
$timeout(function() {
// Do something...
});
}).catch(function (error) {
vm.error = "Me!";
toastr.error(error);
});
}
我的模拟服务:
beforeEach(function() {
module('httpService', function($provide) {
$provide.factory('httpUsers', function () {
var service = {
getUsers: getUsers
}
function getUsers() {
deferred = $q.defer(); // deferred is a global variable
deferred.resolve([
{ id: 1, firstName: "John", lastName: "Doe" },
{ id: 2, firstName: "Jane", lastName: "Doe" },
{ id: 3, firstName: "Jack", lastName: "Doe" }
]);
return deferred.promise;
};
return service;
});
});
});
返回已解决的承诺一切正常。
但是,我想在控制器的init函数中测试catch
子句。
我试过这个:
describe('init', function() {
it('should throw error', function () {
deferred.reject('testing');
expect(controller.error).toBe("Error!"); // NOTE: 'vm' is set to 'this', so controller is 'vm'
});
});
但我得到的只是:
Expected undefined to be 'Error!'.
我没有'测试','我!'或'错误!'。如何强制拒绝我的测试中的承诺?
谢谢!
修改
这是我的控制器注入:
beforeEach(inject(function(_$controller_, _$rootScope_, _$q_, _$timeout_, _global_) {
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$q = _$q_;
$timeout = _$timeout_;
global = _global_;
controller = _$controller_('usersController', {
$rootScope: $rootScope,
$scope: $scope,
$q: $q
});
$timeout.flush();
}));
答案 0 :(得分:1)
如下所示: - 你的模拟服务
beforeEach(function() {
module('httpService', function($provide) {
$provide.factory('httpUsers', function () {
var service = {
getUsers: getUsers
}
function getUsers() {
deferred = $q.defer(); // deferred is a global variable
return deferred.promise;
};
return service;
});
});
});
您的拒绝测试
describe('init', function() {
it('should throw error', function () {
deferred.reject('testing');
$scope.$apply();
expect(controller.error).toBe("Error!");
});
});
您的解决方案
describe('init', function() {
it('should throw error', function () {
deferred.resolve([
{ id: 1, firstName: "John", lastName: "Doe" },
{ id: 2, firstName: "Jane", lastName: "Doe" },
{ id: 3, firstName: "Jack", lastName: "Doe" }
]);
$scope.$apply();
$timeout.flush();
expect(controller.error).toBe("Error!");
});
});