简体   繁体   中英

Jasmine unit test cases

I am new to Jasmine tests and have not able been able to find a solution for this after trying many ways. Can anybody suggest a test case for this code which is in 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 () {
    });

The following test assumes that you are using angular ui bootstraps $modal. This code is untested, but should be fairly close to what you need to get started.

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);
}));

According to your comment, you are doing the following in your test:

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(); 
});

This tells me you are wrapping $modal.open() in a service called commonService.openModal() . My original test still applies, you just need to change this line:

spyOn($modal, 'open').and.returnValue({result: deferred.promise});

to this:

spyOn(commonService, 'openModal').and.returnValue({result: deferred.promise});

You also no longer need to inject $modal as I have done. If this doesn't make sense to you, you should start with more simple tests to understand testing angular with jasmine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM