2014-07-23 86 views
0

我有一個指令,其中有一個鏈接,點擊時顯示模式彈出窗口中的數據。單元測試Angularjs bootstrap Modal

如何爲單擊鏈接編寫單元測試(jasmine),以及如何測試打開模型並正確顯示模式中的數據。

您能提供任何參考嗎?

這裏是我想要的測試

angular.module(’sample', [ 
    'ui.bootstrap' 
]) 
.controller(’ employeeController 

」,[ '$範圍', '$模式',函數($範圍,$模式){

$scope.clickMe = function() { 
     var ModalInstanceCtrl = $modal.open({ 
      templateUrl: ‘template/empView.html', 
      controller: ‘employeeController', 
      resolve: { 
       employees: function() { 
        return $scope.depEmps; 
       } 
      }, 
      size: 'lg' 
     }); 
    }; 

}]).directive(‘empInfo', function() { 
    return { 
     restrict: 'E', 
     templateUrl: ‘asdf, 
     replace: true, 
     controller: 'employeeController', 
     scope: { 
      employees: "=" 
     } 
    }; 
}) 

我想檢查何時調用ClickMe時模型已打開並且數據在模型中正確填充。截至目前,該模型僅在退出鍵按下時關閉。

回答

1

首先,你必須創建一個模式模擬:

function ModalMock { 
    this.open = function(modalArgs) { 
    return 
    }; 
} 

然後初始化這個在您的測試:

beforeEach(() => { 
     // create mocks 
     modalMock = new ModalMock(); 
     controller = $controller('MyCtrl', { 
     $scope: scope, 
     $modal: modalMock, 

    }); 

}); 

而在實際測試中塊,你應該使用spyon方法:

it('should do something', function() { 

      var modalPromise = q.defer().promise; 

      spyOn(modalMock, 'open').andReturn({ result: modalPromise }); 

      controller.doSomething(arg); 


      // make sure that angular resolves/rejects the deferreds 
      scope.$digest(); 

      // verify that the modal is opened 
      expect(modalMock.open).toHaveBeenCalled(); 

     }); 
+0

我編輯了我想測試的代碼,我有一些語法probs使用你的方法。 – user804401

0

你可以編譯你的指令並用jQuery點擊它,之後你可以創建spi es在「模態」功能上,並期望在模塊上調用「模態」功能。如果你有這樣的事情:

$(element).modal('show'); 

您可以在元和模態函數添加的間諜,並期望模式將與「秀」參數來調用。這就是單元測試,你只需要測試你的邏輯是否有效。如果您需要測試模塊組件,並且它是否正確顯示,那麼需要在E2E測試中進行測試。