我如何测试用Karma嘲笑的承诺?

时间:2016-07-05 13:34:03

标签: angularjs unit-testing mocking promise karma-runner

我的代码是:

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

用Karma测试这个的正确方法是什么?这是我到目前为止所做的:

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

对于我的实际测试:

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

但这并没有多大意义。想法?

1 个答案:

答案 0 :(得分:1)

要测试控制器上的openModal功能,基本上您要验证以下内容(3次测试)

    使用一些特定选项
  1. ModalService.showModal进行调用
  2. 显示模态后,验证then函数是否正在执行其想要执行的操作
  3. 关闭模态时,请验证第二个then函数是否正在执行其想要执行的操作
  4. 首先,您可能需要在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作为参数传递),然后您可以验证其行为。

    与验证第二个回调类似,您需要模拟已解析的modal对象。