你如何测试延迟的角度承诺?

时间:2015-08-12 13:56:38

标签: javascript angularjs unit-testing promise angular-promise

如何使用模拟的角度和一段时间后解决的承诺来运行测试?

更简单地说:下面的测试永远不会运行

var injector = angular.injector(['ngMock']);
var scope = injector.get('$rootScope').$new();
var q = injector.get('$q');

var promise = function() {
  return q(function(resolve, reject) {
    setTimeout(function() {
      resolve();
    }, 500);
  });
};

promise()
  .then(function() {
    document.getElementById('result').innerHTML = 'TEST RUN';
  });

//resolve the promises
scope.$digest();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular-mocks.js"></script>
<p id="result">starting test...</p>

1 个答案:

答案 0 :(得分:1)

显然,$q与角度中的$ rootScope.Scope Scope模型观察机制集成在一起,这意味着更快地将分辨率或拒绝传播到模型中,并避免不必要的浏览器重绘,这将导致UI闪烁。 (有关详细信息,请检查docs中Q和$ q之间的差异)。我刚刚在您的代码段中添加了scope.$apply()

&#13;
&#13;
var injector = angular.injector(['ngMock']);
var scope = injector.get('$rootScope').$new();
var q = injector.get('$q');

var promise = function() {
  return q(function(resolve, reject) {
    setTimeout(function() {
      resolve();
      scope.$apply();
    }, 500);
  });
};

promise()
  .then(function() {
    document.getElementById('result').innerHTML = 'TEST RUN';
  });

//resolve the promises
scope.$digest();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular-mocks.js"></script>
<p id="result">starting test...</p>
&#13;
&#13;
&#13;