我是Jasmine测试的新手,并且在尝试了很多方法之后无法找到解决方案。任何人都可以为AngularJS中的代码建议一个测试用例吗?
modalInstance.result.then(function (modalOutput) {
if (modalOutput) {
if ('okToUndoEdits' === modalOutput[1]) {
$scope.chargebackDetail.cbDetails = angular.copy($scope.chargebackDetailBackup.cbDetails);
} else if ('okToSaveUnmatched' === modalOutput[1]) {
$('#noMatchWarning').show();
$scope.isMatchedDoc = false;
}
}
}, function () {
});
答案 0 :(得分:0)
以下测试假定您使用的是角度ui bootstraps $ modal。此代码未经测试,但应该与您开始使用的内容非常接近。
it('should revert chargebackDetail.cbDetails to the backup, if it is ok to undo edits', inject(function($modal, $q) {
// Arrange
$scope.chargebackDetail = {};
$scope.chargebackDetailBackup = {cbDetails: [11, 13, 17]};
var deferred = $q.defer();
spyOn($modal, 'open').and.returnValue({result: deferred.promise});
// Act
$scope.whateverYourFunctionIsCalled();
deferred.resolve([null, 'okToUndoEdits']);
$scope.$apply();
// Assert
expect($scope.chargebackDetail.cbDetails).toEqual($scope.chargebackDetailBackup.cbDetails);
expect($scope.chargebackDetail.cbDetails).not.toBe($scope.chargebackDetailBackup.cbDetails);
}));
根据您的评论,您在测试中正在执行以下操作:
it('should get open', function() {
spyOn(commonService, 'openModal').and.callFake(function() {
return {
// Create a mock object using spies
close: jasmine.createSpy('modalInstance.close'),
dismiss: jasmine.createSpy('modalInstance.dismiss'),
result: {
then: jasmine.createSpy('modalInstance.result.then')
}
};
});
scope.open();
});
这告诉我你将$modal.open()
包装在一个名为commonService.openModal()
的服务中。我的原始测试仍然适用,您只需更改此行:
spyOn($modal, 'open').and.returnValue({result: deferred.promise});
到此:
spyOn(commonService, 'openModal').and.returnValue({result: deferred.promise});
你也不再需要像我一样注入$ modal。如果这对你没有意义,你应该从更简单的测试开始,以了解用茉莉花测试角度。