Karma-Jasmine: How to properly spy on a Modal?

走远了吗. 提交于 2019-12-01 09:28:22

The question here could be extrapolated to how to properly spy on a promise. You are very much on the right track here.

However, if you want to test that whatever your callback to the success of the promise is called, you have to execute two steps:

  1. Mock the service (in your case $ionicModal) and return some fake function
  2. In that fake function, execute the callback that is passed to you by the production code.

Here is an illustration:

//create a mock of the service (step 1)
var $ionicModal = jasmine.createSpyObj('$ionicModal', ['fromTemplateUrl']);

//create an example response which just calls your callback (step2)
var successCallback = {
   then: function(callback){
       callback.apply(arguments);
   }
};

$ionicModal.fromTemplateUrl.and.returnValue(successCallback);

Of course, you can always use $q if you don't want to be maintaining the promise on your own:

//in your beforeeach
var $ionicModal = jasmine.createSpyObj('$ionicModal', ['fromTemplateUrl']);
//create a mock of the modal you gonna pass and resolve at your fake resolve
var modalMock = jasmine.createSpyObj('modal', ['show', 'hide']);
$ionicModal.fromTemplateUrl.and.callFake(function(){
    return $q.when(modalMock);
});


//in your test
//call scope $digest to trigger the angular digest/apply lifecycle
$scope.$digest();
//expect stuff to happen
expect(modalMock.show).toHaveBeenCalled();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!