简体   繁体   English

使用Angular Promise进行Jasmine测试无法使用TypeScript解决

[英]Jasmine Testing with Angular Promise not resolving with TypeScript

I have a fairly straightforward test that works against an Angular promise, which I'm resolving in the beforeEach function, but the then in my code is not ever firing and I can't see what I'm missing. 我有一个相当简单的测试,可以对Angular promise进行工作,我在beforeEach函数中解决了这个问题,但是代码中的then从来没有触发过,我看不到我所缺少的东西。 These are written with TypeScript, but that doesn't really have any bearing on the problem. 这些都是用TypeScript编写的,但实际上与该问题没有任何关系。

Here is my test 这是我的测试

describe('Refresh->', () => {

  var controller = new Directives.Reporting.ReportDirectiveController($scope, $q, $location);
  var called = false;
  var defer: any;

  beforeEach((done) => {
    controller.drillReport = (drillReport: Models.drillReport): ng.IPromise<Models.drillData> => {
      defer = $q.defer();
      called = true;
      defer.resolve({});
      return defer.promise;
    };
    spyOn(controller, 'processResults');
    controller.refresh();
    done();
  });

  it('Calls DrillReport', () => {
    expect(called).toBeTruthy();
  });

  it('Calls ProcessResults', () => {
    expect(controller.processResults).toHaveBeenCalled();
  });
});

The Refresh method in the controller looks like this: 控制器中的Refresh方法如下所示:

refresh() {
  this.drillReport({ drillReport: drillReport })
    .then((results: Models.drillData) => {
      parent.processResults(results, parent.availableDrills, this.columns, this.gridOptions, undefined, undefined);
    });
}

What you are missing is that you will need access to use $scope , or $rootScope , so that you can call and force a digest cycle... 您所缺少的是您将需要访问使用$scope$rootScope ,以便可以调用并强制执行摘要循环。

$scope.$digest();

The reason this is needed is that the resolved and rejected promises are processed during the digest loop. 之所以需要这样做,是因为在摘要循环中处理了已解决和已拒绝的承诺。 So while you are resolving the promise in your mock, the actual promise callback is not being invoked. 因此,当您在模拟中解析诺言时,实际的诺言回调不会被调用。

Following up on what @Brocco said, your code is calling done() before the promise is processed. 遵循@Brocco所说的内容,您的代码在处理Promise之前调用了done()。

What you need it a way for your test code to know that that parent.processResults() has been called. 您需要的是一种让测试代码知道已调用parent.processResults()

I suggest you have refresh return a promise that will be resolved just after parent.processResults() , and add controller.refresh().finally(() => { done(); }); 我建议您刷新后返回一个诺言,该诺言将在parent.processResults()之后解决,并添加controller.refresh().finally(() => { done(); }); in your test code. 在您的测试代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM