我的 Controller 的初始化:
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;
});
});
});
返回已解决的 promise 一切正常。
但是,我想测试 Controller 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'
});
});
但我得到的是:
预期未定义为“错误!”。
我没有收到“测试”、“我!”或“错误!”。如何强制拒绝测试中的 promise ?
谢谢!
编辑
这是我的 Controller 注入(inject):
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();
}));
最佳答案
如下所示:- 您的模拟服务
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!");
});
});
关于javascript - Jasmine 回归被 mock 工厂的 promise 被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34867639/