如何用chai-as-promise和karma / angular来模拟延迟?

时间:2016-04-06 22:56:08

标签: angularjs karma-runner chai karma-mocha chai-as-promised

伪造延迟承诺解决方案的示例测试:

describe('Example', function() {
  var $q;
  var $rootScope;
  var $scope;
  var $timeout;
  var fakePromise;

  beforeEach(inject(function (_$q_, _$rootScope_, _$timeout_) {
    $q = _$q_;
    $rootScope = _$rootScope_;
    $timeout = _$timeout_;
    $scope = $rootScope.$new();

    fakePromise = function (){
      return new Promise(function(resolve, reject){
        $timeout(function(){
          resolve('foo');
        }, 100);
      });
    };
  }));

  afterEach(function () {
    $scope.$apply();
  });

  it('should wait for promise to resolve and have a result', function(){
    return fakePromise().should.eventually.equal('foo'); //taken from chai-as-promised readme
  });

});

自述文件说:

return doSomethingAsync().should.eventually.equal("foo");

我得到的错误是:

Chrome 49.0.2623 (Mac OS X 10.11.4) Example should wait for promise to resolve and have a result FAILED
  Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

1 个答案:

答案 0 :(得分:0)

$timeout服务已经返回一个承诺。无需制造。

fakePromise = $timeout(function() {return "foo"}, 100);

在此示例中,fakePromise设置为一个解析为" foo" 100毫秒后。