0

我有一个包含以下方法的 Angular 服务:

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

如何测试$mdDialog 的onComplete回调?我已经设法测试是否调用了 $mdDialog.show 但我无法让测试回调工作。

4

1 回答 1

4

$mdDialog.show()在单元测试期间不会自行解决。要模拟该行为,您需要在测试中覆盖 show 方法并自己调用 onComplete 函数。一个简单的示例如下所示:

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

// Call your function
showDialog();

但是,这忽略了通常由$mdDialog.show(). 支持承诺链的更完整的覆盖,即$mdDialog.show().then(),需要返回一个虚拟承诺并手动解决它:

// 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();
于 2016-02-18T16:43:12.560 回答