以下是我试图进行单元测试的部分控制器的代码,但我没有太多运气。我一直收到错误消息错误:spyOn找不到要监视帐户()的对象。
控制器
$scope.confirmDelete = function (account) {
var modalInstance = $modal.open({
templateUrl: '/app/accounts/views/_delete.html',
controller: function (global, $scope, $modalInstance, account) {
$scope.account = account;
$scope.delete = function (account) {
global.setFormSubmitInProgress(true);
accountService.deleteAccount(global.activeOrganizationId, account.entityId).then(function () {
global.setFormSubmitInProgress(false);
$modalInstance.close();
},
function (errorData) {
global.setFormSubmitInProgress(false);
});
};
$scope.cancel = function () {
global.setFormSubmitInProgress(false);
$modalInstance.dismiss('cancel');
};
},
resolve: {
account: function () {
return account;
}
}
});
modalInstance.result.then(function (asset) {
$scope.getAll(1, 100);
}, function () {
console.log('Modal dismissed at: ' + new Date());
});
};
测试
describe("confirmDelete() function", function () {
var controller, scope;
// sets scope of controller before each test
beforeEach(inject(function ($rootScope, _$modal_) {
scope = $rootScope.$new();
controller = $controller('AccountsController',
{
$scope: scope,
$stateParams: mockStateParams,
$state: mockState,
// below: in order to call the $modal have it be defined and send on the mock modal?
$modal: _$modal_,
//modalInstance: mockModalInstance,
global: mockGlobal,
accountService: mockAccountSrv
});
}));
beforeEach(inject(function ($modal) {
spyOn($modal, 'open');
spyOn(scope.modalInstance, "account");
}));
it("make sure modal promise resolves", function () {
scope.confirmDelete(mockAccountSrv.account);
expect($modal.open).toHaveBeenCalled();
});
});
答案 0 :(得分:3)
问题是在第二个beforeEach
中你试图窥探scope.modalInstance
并且这样的字段不存在。因此,Jasmine无法找到窥探的对象。
另一个问题是你使用模态的result
承诺,所以你告诉你的模型返回它以便不得到TypeError。
beforeEach(inject(function ($modal, $q) {
spyOn($modal, 'open').and.returnValue({
result: $q.defer().promise
});
)
下一步将返回您可以在单元测试中解析的承诺,以便在解析或拒绝时验证正确的行为。您可以通过这种方式模拟模态窗口关闭。
在Jasmine docs中了解有关间谍的更多信息。
另请注意,您不必将模态服务注入控制器(我的意思是$modal: _$modal_
行)。服务是单身人士。当你监视它的任何一个实例时,它会在任何地方窥探它。