Testing AngularUI Bootstrap modal instance controller

后端 未结 4 805
醉话见心
醉话见心 2020-12-05 07:32

This is a somewhat of a follow-on question to this one: Mocking $modal in AngularJS unit tests

The referenced SO is an excellent question with very useful answer. Th

4条回答
  •  生来不讨喜
    2020-12-05 07:33

    Alternatively, if you're using jasmine, you can mock the $uibModalInstance using the createSpy method:

    beforeEach(inject(function ($controller, $rootScope) {
      $scope = $rootScope.$new();
      $uibModalInstance = jasmine.createSpyObj('$uibModalInstance', ['close', 'dismiss']);
    
      ModalCtrl = $controller('ModalCtrl', {
        $scope: $scope,
        $uibModalInstance: $uibModalInstance,
      });
    }));
    

    And test it without having to call spyOn on each method, let's say you have 2 scope methods, cancel() and confirm():

    it('should let the user dismiss the modal', function () {
      expect($scope.cancel).toBeDefined();
      $scope.cancel();
      expect($uibModalInstance.dismiss).toHaveBeenCalled();
    });
    
    it('should let the user confirm the modal', function () {
      expect($scope.confirm).toBeDefined();
      $scope.confirm();
      expect($uibModalInstance.close).toHaveBeenCalled();
    });
    

提交回复
热议问题