AngularJS $timeout 函数未在我的 Jasmine 规范中执行 [英] AngularJS $timeout function not executing in my Jasmine specs

查看:20
本文介绍了AngularJS $timeout 函数未在我的 Jasmine 规范中执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Karma 测试我的 AngularJS 控制器和 Jasmine.但是在现实生活中运行良好的 $timeout 会使我的测试崩溃.

I'm trying to test my AngularJS controller with Jasmine, using Karma. But a $timeout which works well in real-life, crashes my tests.

控制器:

var Ctrl = function($scope, $timeout) {
  $scope.doStuff = function() {
    $timeout(function() {
      $scope.stuffDone = true;
    }, 250);
  };
};

Jasmine it 块(其中 $scope 和控制器已正确初始化):

Jasmine it block (where $scope and controller have been properly initialized):

it('should do stuff', function() {
  runs(function() {
    $scope.doStuff();
  });
  waitsFor(function() { 
    return $scope.stuffDone; 
  }, 'Stuff should be done', 750);
  runs(function() {
    expect($scope.stuffDone).toBeTruthy();
  });
});

当我在浏览器中运行我的应用程序时,将执行 $timeout 函数并且 $scope.stuffDone 将为真.但在我的测试中,$timeout 什么都不做,该函数永远不会执行,并且 Jasmine 在超时 750 毫秒后报告错误.这里可能有什么问题?

When I run my app in browser, $timeout function will be executed and $scope.stuffDone will be true. But in my tests, $timeout does nothing, the function is never executed and Jasmine reports error after timing out 750 ms. What could possibly be wrong here?

推荐答案

根据$timeout<的Angular JS文档/a>,可以使用$timeout.flush()同步刷新延迟函数队列.

According to the Angular JS documentation for $timeout, you can use $timeout.flush() to synchronously flush the queue of deferred functions.

尝试将您的测试更新为:

Try updating your test to this:

it('should do stuff', function() {
  expect($scope.stuffDone).toBeFalsy();
  $scope.doStuff();
  expect($scope.stuffDone).toBeFalsy();
  $timeout.flush();
  expect($scope.stuffDone).toBeTruthy();
});

这是一个 plunker,显示您的原始测试失败和新测试通过.

Here is a plunker showing both your original test failing and the new test passing.

这篇关于AngularJS $timeout 函数未在我的 Jasmine 规范中执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆