【问题标题】:How to simulate time passing in angularjs test?如何模拟 angularjs 测试中的时间传递?
【发布时间】:2014-07-30 22:56:13
【问题描述】:

我正在尝试通过 angularjs jasmine 测试通过模拟时间。

我正在测试的指令只是显示当前时间并每秒更新一次:

return {
  restrict: 'A',
  scope: {
    format: '@'
  },
  link: function (scope, element, attrs) {

    var timeout;

    function updateElement() {
      if (scope.format) {
        element.text($filter('date')(new Date(), scope.format));
      }
    }

    function updateTime() {
      updateElement();
      timeout = $timeout(function () {
        updateTime();
      }, 1000);
    }

    element.bind('$destroy', function () {
      $timeout.cancel(timeout);
    });

    updateTime();
  }
};

在我的测试中,我需要模拟时间流逝。我尝试使用 $timeout 和 $timeout.flush 但我认为我用错了:

it('should update every second', function () {
  $scope.$digest();
  console.log('before: ' + element.text());
  var before = element.text();

  // Wait for a couple seconds...
  $timeout(function () {
    $scope.$digest();
    console.log('after: ' + element.text());
    expect(element.text()).not.toEqual(before);
  }, 5000);

  $timeout.flush(5000);
});

我应该使用 $timeout 来模拟时间流逝还是他们的另一种方法?

Plunker:http://plnkr.co/edit/0V4AFGXqSfc9iLCuZbvn?p=preview

【问题讨论】:

    标签: angularjs angularjs-directive timeout jasmine


    【解决方案1】:

    如果您将$scope.$digest() 包装在setTimeout 中,它应该可以工作。像这样:

    setTimeout(function(){
      $timeout.flush();
      console.log('after: ' + element.text());
      expect(element.text()).not.toEqual(before);
    }, 5000);
    

    $timeout.flush() 通过调用$timeout 注册的所有回调来在测试中工作,而不管它们的时间值如何,因此在这种情况下,您必须在角度之外进行超时。由于您每秒都在寻找更改,因此您的代码将在一秒钟内调用 updateElement() 两次。

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2014-02-08
      相关资源
      最近更新 更多