Jasmine异步测试在SpecRunner中传递,但是从命令行失败(grunt-contrib-jasmine)

时间:2014-01-14 22:37:13

标签: javascript ajax tdd jasmine

我测试了一个方法,如果我通过SpecRunner运行它会通过但是如果我从命令行运行测试会失败(例如grunt jasmine)。

测试如下所示。 doSomething()方法进行AJAX调用并使用响应在DIV中创建一个UL元素,id =" my-test"。

describe( 'my AJAX method', function() {
 beforeEach( function() {
   this.$myTest = $('<div id="my-test"></div>');
   this.$myTest.appendTo($('body'));
 });
 afterEach( function() {
   this.$myTest.remove();
 });
 it('should create a UL from the result of the Ajax request', function() {
   runs(function() {
     myObj.doSomething();  // this makes an AJAX request and builds a UL from the response
   });
   waitsFor(function() {
     return( this.$myTest.find('ul').length > 0 );
   }, 'UL has been created', 2000);
   runs( function() {
     expect(this.$myTest.find('ul').length).toEqual(1);
   });
 });
});

命令行的错误消息是: -

Running "jasmine:src" (jasmine) task
Testing jasmine specs via phantom
............x
my AJAX method:: should create a UL from the result of the Ajax request: failed
 timeout: timed out after 2000 msec waiting for UL has been created (1)
13 specs in 1.749s.
>> 1 failures
Warning: Task "jasmine:src" failed. Use --force to continue.

Aborted due to warnings.

有谁知道为什么会这样?

1 个答案:

答案 0 :(得分:0)

我发现使用grunt-contrib-jasmine时不会立即创建body元素,因此你的#my-test div可能不会附加到body元素上。你可以尝试

$('body').ready(function {
    // Do stuff with body.
});

如果你正在使用jQuery。

老问题,但也许它可以帮助有人搜索。