【问题标题】:Error: Timeout - Async callback was not invoked within timeout specified.... .DEFAULT_TIMEOUT_INTERVAL错误:超时 - 在指定的超时时间内未调用异步回调.... .DEFAULT_TIMEOUT_INTERVAL
【发布时间】:2015-03-24 07:20:27
【问题描述】:

我有一个角度服务类:-

angular.module('triggerTips')
       .service('userData', function ($rootScope, $http, $log, $firebase) {

    this._log = {
        service : 'userData'
    };

    // Synchronized objects storing the user data
    var config;
    var userState;

    // Loads the user data from firebase
    this.init = function(readyCallback) {
        var log = angular.extend({}, this._log);
        log.funct = 'init';

        var fireRef = new Firebase('https://XYZfirebaseio.com/' + $rootScope.clientName);
       config = $firebase(fireRef.child('config')).$asObject();
       userState = $firebase(fireRef.child('userState').child($rootScope.userName)).$asObject();

  Promise.all([config.$loaded(), userState.$loaded()]).
    then(
      function() {
        if(config == null || Object.keys(config).length < 4) {
          log.message = 'Invalid config';
          $log.error(log);
          return;
        }

        if(!userState.userProperties) {
          userState.userProperties = {};
        }

        if(!userState.contentProperties) {
          userState.contentProperties = {};
        } 

        log.message = 'User Properties: ' + JSON.stringify(userState.userProperties);
        $log.debug(log);

        log.message = 'Content Properties: ' + JSON.stringify(userState.contentProperties);
        $log.debug(log);

        log.message = 'Loaded user data from firebase';
        $log.debug(log);
        readyCallback();
      },
      function() {
        log.message = 'Unable to load user data from firebase';
        $log.error(log);
      }
    );
};

// Returns the initial tip configuration
this.getConfig = function() {
  return config;
};

// Set the value of a user property
// A user property is something about the user himself
this.setUserProperty = function(property, value) {
  if(!userState.userProperties) {
    userState.userProperties = {};
  }
  userState.userProperties[property] = value;
  userState.$save();
  $rootScope.$broadcast('user-property-change', property);
};

// Get the value of a user property
this.getUserProperty = function(property) {
  if(userState.userProperties) {
    return userState.userProperties[property];
  }
};

// Set the value of a user content property
// A content property is something about a particular peice of content for a particular user
this.setContentProperty = function(contentName, property, value) {
  if(!userState.contentProperties[contentName]) {
    userState.contentProperties[contentName] = {};
  }

  userState.contentProperties[contentName][property] = value;
  userState.$save();
  $rootScope.$broadcast('content-property-change', contentName, property);
};

// Increment a count property on the user state for a given tip
this.incrementContentProperty = function(contentName, property) {
  if(!userState.contentProperties[contentName]) {
    userState.contentProperties[contentName] = {};
  }
  if(!userState.contentProperties[contentName][property]) {
    userState.contentProperties[contentName][property] = 0;
  }

  userState.contentProperties[contentName][property]++;
  userState.$save();
  $rootScope.$broadcast('content-property-change', contentName, property);
};

// Returns the user state for a given tip and property
this.getContentProperty = function(contentName, property) {
  if(userState.contentProperties) {
    var t = userState.contentProperties[contentName];
    if(t) {
      return t[property];
    }
  }
};
});

我正在尝试使用 jasmine 对该服务进行单元测试:-

我的单元测试是:-

    'use strict';

describe('Service: userData', function () {

  // load the service's module
  beforeEach(function() {
    module('triggerTips');
  });

  // instantiate service
  var userData;
  beforeEach(inject(function (_userData_) {
    userData = _userData_;
  }));

  it('should load correctly', function () {
    expect(!!userData).toBe(true);
  });

  describe('after being initialized', function () {

    beforeEach(function(done) {
      // Unable to get this working because the callback is never called
        userData.init(function() {
            done();
        });
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
    });

    it('should have a valid config', function (done) {
         setTimeout(function() {
             expect(Object.keys(userData.getConfig()).length == 0);
             done();
           }, 1500);}); }); });

我阅读了有关 Jasmine 中的异步支持的信息,但由于我对使用 JavaScript 进行单元测试比较陌生,因此无法使其工作。

我收到一个错误:

在指定的超时时间内未调用异步回调 jasmine.DEFAULT_TIMEOUT_INTERVAL

有人可以帮我提供我的代码的工作示例和一些解释吗?

【问题讨论】:

  • readyCallback 在 promise 被解决时被调用。您需要解决承诺并触发摘要,请参阅docs.angularjs.org/api/ng/service/…
  • 感谢您的回复,我如何在不更改服务的情况下进行更正,请帮我解决这个问题
  • 您不需要更改源代码。您应该对 config 和 userState 使用模拟,并在其 $loaded 函数上返回已解决的承诺,然后在您的测试中调用 $scope.$apply。如果你用你的代码设置一个小提琴,我可以在那里展示它。
  • littel 明白你的意思,你能帮我做一个测试用例吗?这对我很有帮助
  • 尝试删除'done'参数。受 [this question][1] 启发的答案。 [1]:stackoverflow.com/questions/22604644/…

标签: angularjs unit-testing asynchronous jasmine


【解决方案1】:

我建议您将 setTimeout 替换为 $timeout 以加快您的规范套件。您将需要 ngMock 成为您的规范套件的一部分,以使其以预期的方式工作,但这似乎已经考虑到您的规范。好东西。

然后为了使规范的异步特性“消失”,您可以调用:

$timeout.flush([delay]) 其中delay 是可选的。

  • 如果没有延迟,所有待处理的异步任务(在 Angular 世界中)都会完成它们正在做的事情。
  • 如果经过延迟,则指定延迟内的所有待处理任务都将完成。超出指定延迟的那些将保持“待定”状态。

这样,您可以删除done 回调并编写您的测试:

describe('after being initialized', function () {
  var $timeout;

  beforeEach(function () {
    // Unable to get this working because the callback is never called
    userData.init();

    inject(function ($injector) {
      $timeout = $injector.get('$timeout');
    });
  }));

  it('should have a valid config', function () {
    $timeout.flush();
    // callback should've been called now that we flushed().
    expect(Object.keys(userData.getConfig()).length).toEqual(0);
  });
});

您使用的是什么Promise 实现?我看到了对Promise.all 的调用,但为了继续我的回答,我将假设它等同于$q.all。运行 $timeout.flush 应该负责解析这些值。

如果你想在 Jasmine 中对 promise 的被拒绝/已解决的值写期望,我会研究 jasmine-promise-matchers 之类的东西,让它干净漂亮,但除非你可以这样做:

// $q
function get () {
  var p1 = $timeout(function () { return 'x'; }, 250);
  var p2 = $timeout(function () { return 'y'; }, 2500); 

  return $q.all([p1, p2]);
}

// expectation
it('is correct', function () {
  var res; 

  get().then(function (r) {
    res = r;
  });

  $timeout.flush(2500);

  expect(res).toEqual(['x', 'y']);
});

根据您的设置,您可能需要也可能不需要存根/监视(取决于您的框架对 spy 的定义)与本地 config 变量相关的承诺,但是我认为这完全是另一个故事。

我对 $firebase(something).$asObject.$loaded 一点也不熟悉 - 因此我可能在这里错过了一些东西,但假设它“就像任何其他承诺一样”你应该很好去吧。

jsfiddle

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-07-24
    • 2016-04-21
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多