angularjs - 错误 : Timeout - Async callback was not invoked within timeout specified. ... .DEFAULT_TIMEOUT_INTERVAL

标签 angularjs unit-testing asynchronous jasmine

我有一个 angular.service 类:-

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 进行单元测试比较陌生,因此无法使其工作。

我收到一个错误:

Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL



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

最佳答案

我建议你更换 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 的定义)与本地相关的 promise config变量,但我认为这完全是另一个故事。

    我对 $firebase(something).$asObject.$loaded 一点都不熟悉——因此我可能在这里错过了一些东西,但假设它像任何其他 promise 一样有效,你应该很高兴。

    jsfiddle

    关于angularjs - 错误 : Timeout - Async callback was not invoked within timeout specified. ... .DEFAULT_TIMEOUT_INTERVAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29226940/

    相关文章:

    javascript - Angular - $q 未按预期工作/帮助等待 $http 完成

    javascript - 多图片src路径切换

    c# - 单元测试添加/获取方法对

    unit-testing - Ember.js 中的单元测试

    c++ - 如何在传递给模拟方法的对象上调用方法

    vb.net - Async Sub() 或 Async Function() 作为即发即弃的任务?

    android - 多个http请求的架构

    javascript - 在 AngularJS 中评估指令属性中的表达式

    javascript - 将 javascript 数组值分配给 angularjs 变量

    javascript - 从匿名函数作用域中提取数据