How can I test a promise that is taunted with karma?

My code is:

  $scope.openModal = openModal;


  function openModal(data){
    var info = data || {}
    ModalService.showModal({
        templateUrl: ENVApp+"/myview.html",
        controller: "ModalController",
        inputs: {
          icon : "",
          title: "Additional",
          data : info
        }
      }).then(function (modal) {
        modal.element.modal();
        modal.close.then(function (res) {
          if(res.data != 'cancel'){
            if(!res.data.id){
              create(res)
            }else{
              update(res)
            }
          }
        });
      });
  }

What is the right way to test this with karma? Here is what I still have:

in mine beforeEach:

  this.ModalService = {
    showModal: function(obj) {
      var deferred = $q.defer();
      deferred.resolve({
        element: {
          modal: jasmine.createSpy(),
          close: function() {
            var deferred2 = $q.defer();

            return deferred2.promise;
          }
        }
      });
      return deferred.promise;
    }
  };
  this.UserService = {
    user: {
      id: 2
    },
    updateCategory: function(data, type) {
      var deferred = $q.defer();
      deferred.resolve({
        data: {
          rows: 'response'
        }
      });
      return deferred.promise;
    }
  }
  this.controller = $controller('ProfileAdditionalController', {
    '$scope': this.scope,
    '$rootScope': this.rootScope,
    '$state': this.state,
    "$stateParams": this.stateParams,
    'ModalService': this.ModalService,
    'UserService': this.UserService,
    'ResourceService': this.ResourceService,
    '$upload': this.upload,
    'userData': this.userData
  });

For my actual test:

  it('should open a modal when requested', function() {
    this.scope.openModal();
    expect(this.ModalService.showModal)
  });

But that doesn't make much sense. Thoughts?

+4
source share
1 answer

To test your function openModalon your controller, basically you want to check the following (3 tests)

  • ModalService.showModal called with some specific options
  • After displaying the modality, make sure that the function thendoes what it should do.
  • , , then ,

-, , , (mock) ModelService.showModal: spyOn(ModalService, 'showModal).and.returnValue($q.when(mockModal))

$scope. $digest call:

$scope.openModal(data);
$scope.$digest() // to propagate the `resolve()` result of the promise)

then ( mockModal ), .

2- modal.

+1

All Articles