$uibModal.open 不是业力函数(AngularJS 工厂)

$uibModal.open is not a function in karma (AngularJS Factory)

我正在尝试测试一个打开 $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;
      });
    });
  });

之后我用 beforeEach 注入 opendismissclose 函数。

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 不是一个函数 .

你的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。当你有相应的代码时,它们很有用。