$ uibModal.open不是业力中的函数(AngularJS Factory)

时间:2017-04-04 09:09:10

标签: angularjs angular-ui-bootstrap karma-runner

我正在尝试测试打开$uibmodal的函数。这是我的工厂功能。

confirmationMessage: function (message) {
    var modalInstance = $uibModal.open({
      templateUrl: 'views/templates/utilsTemplates/confirmationMessage.html',
      backdrop: 'static',
      controller: function () {
        var messageCtrlVM = this;
        // message to show
        messageCtrlVM.message = message;
        // when yes_button is pressed
        messageCtrlVM.yesPress = function () {
          modalInstance.close(true);
        };
        // when no_button is pressed
        messageCtrlVM.noPress = function () {
          modalInstance.close();
        };
      },
      controllerAs: "messageCtrlVM"
    });
    return modalInstance.result;
  },

在其单元测试文件中,我首先为此添加提供程序。

beforeEach(angular.mock.module('ui.bootstrap'));

beforeEach(function () {
    module(function ($provide) {
      $provide.value('$uibModal', function (value) {
        return value;
      });
    });
  });

之后,我正在open注入dismissclosebeforeEach函数。

beforeEach(inject(function (_utilsFactory_, _$httpBackend_, _$filter_) {
  utilsService = _utilsFactory_;
  $httpBackend = _$httpBackend_;
  filter = _$filter_;
  uibModal = {
    open: function () {},
    dismiss: function () {},
    close: function () {}
  };

}));

最后,我试图通过调用工厂函数来运行我的单元测试。

it('should show a confirmation message', function () {
  var spy = spyOn(uibModal, "open").and.callFake(function () {
    return {
      result: {
        then: function () {}
      }
    };
  });
  utilsService.confirmationMessage("Are you Sure?");
  expect(spy).toHaveBeenCalled();

});

我错误地认为 $uibModal.open不是函数

1 个答案:

答案 0 :(得分:1)

您的beforeEach应该是这样的:

beforeEach(module('myApp', function ($provide) {

    mockModal = {
        result: {
            then: function(confirmCallback, cancelCallback) {
                this.confirmCallback = confirmCallback;
                this.cancelCallback = cancelCallback;
                return this;
            }
        },
        opened: {
            then: function (confirmCallback, cancelCallback) {
                this.confirmCallback = confirmCallback;
                this.cancelCallback = cancelCallback;
                return this;
            }
        },
        close: function() {
            this.opened.confirmCallback(); // covers opened.then success
            this.result.confirmCallback(); // covers result.then success
            this.result.cancelCallback(); // covers result.then error
        },
        open: function (object1) {
            return this;
        }
    };
    $provide.value('$uibModal', mockModal);
}));

请注意,在这里,我们提供的$uibModal对象具有open功能。$provide传递此内容后,您需要callThrough(间谍后不是callFake

如果您不在此处使用,请随时删除result / opened / close。当你有相应的代码时,它们很有用。