Unit test onComplete callback for $mdDialog

2.8k Views Asked by At

I have an Angular service that contains the following method:

function showDialog() {
    $mdDialog.show({
        controller: 'SampleCtrl',
        controllerAs: 'vm',
        bindToController: true,
        templateUrl: 'template.html',
        onComplete: function () {
            service.doSomething();
        }
    });
}

How can I test onComplete callback of $mdDialog? I have managed to test if $mdDialog.show is called but I cannot get the test callback to work.

1

There are 1 best solutions below

0
On BEST ANSWER

$mdDialog.show() will not resolve on its own during unit testing. To simulate that behavior, you need to override the show method in your tests and call the onComplete function yourself. A simple example would look something like:

$mdDialog.show = function (options) {
  options.onComplete();
};

// Call your function
showDialog();

However, that ignores the promise normally returned by $mdDialog.show(). A more complete override that supports promise chains, i.e. $mdDialog.show().then(), requires returning a dummy promise and resolving it manually as well:

// Create a dummy promise we can resolve manually
var deferred = $q.defer(); 

$mdDialog.show = function (options) {
  options.onComplete();

  // Return the dummy promise
  return deferred.promise;
};

// Call your function
showDialog();

// Resolve the promise, which won't actually be resolved until apply is called
deferred.resolve();
$rootScope.$apply();