0

我正在尝试使用 Jest 对 Angular UI 运行一个小测试,但我在 5 秒后超时。这是我的代码:

jest.autoMockOff();

require('../../../../bower_components/angular/angular');
require('../../../../bower_components/angular-mocks/angular-mocks');

window.Event = {};

describe('about', function(){

   var mockScope;

   pit('updates the view ', function(done){
        return runTest()
       .then(function(){
           var $ = require('../../../../bower_components/jquery/dist/jquery');
           expect($("#about-div").text()).toEqual('fred');  
       });
    });

    function runTest() {
       var q = require('../../../../bower_components/q/q');
       var defer = q.defer();

       require('../../../../app/scripts/app');
       require('../../../../app/scripts/controllers/about');

       angular.mock.module('app');
       inject(function($rootScope, $controller){
          mockScope = $rootScope.$new();
          controller = $controller('aboutController', {$scope: mockScope});
       });

       document.body.innerHTML =
            '<html>' +
            '   <body>' +
            '      <div ng-controller="aboutController">' +
            '         <div id="about-div" >{{firstName}}</div>' +
            '      </div>' +
            '   </body>' + 
            '</html>';

       setTimeout(function() { defer.resolve(); }, 1000);

       return defer.promise;
   };
});

我正在使用pit,所以我可以有1秒的延迟以允许角度更新视图,但似乎setTimeout中的匿名函数永远不会被调用。承诺没有兑现,测试超时。由于 Jest 使用 Jasmine 1.3.0,我也尝试过使用 runs() 和 waitsFor() 但我得到了相同的结果。

4

1 回答 1

2

也在与这个作斗争,但在我的情况下已经解决了。关键问题是 jest 劫持了您的计时器并将它们放入队列中,除非您明确这样做,否则该队列永远不会运行。

尝试改变

return runTest()
.then(..

queued = runTest(); // run it... jest will hijack your internal timer
jest.runAllTimers(); // kick the timer to get it unstuck...
return queued.then(... // return the promise, having forced the internal timers to run

实际上,并不是这个命令 (jest.runAllTimers) 会启动计时器,而是它将运行计时器内的内容 - 所以你跳过了等待,这可以让你的测试运行得更快。

在这里可以找到有用的背景: https ://facebook.github.io/jest/docs/timer-mocks.html#content

在这里: https ://facebook.github.io/jest/docs/api.html#jest-runalltimers

于 2015-09-24T03:09:00.520 回答