2013-05-13 86 views
0

我剛剛開始使用茉莉花單元測試,並且遇到了一些測試異步調用的麻煩。茉莉花異步調用問題

我有一個ajax調用,我試圖測試,我試着在控制檯中,所以我知道它的工作原理是如何工作的。我想我正在測試我在控制檯中做的同樣的事情,但可能是錯誤的。

這裏是控制檯:

> mg = new MandellMVC() 
MandellMVC {getSessionId: function, setSessionId: function, isValidGetFunction: function, getURLPrefix: function, setURLPrefix: function…} 
> mg.setUseLocalData(true); 
true 
> var log = new Log(73936780) 
undefined 
> log.setLogType('Proc') 
true 
> log.fetch(mg, function(){console.log('done');}) 
true 
done 

設置本地數據只是發送從本地文件的HTTP請求到外部服務器,或加載數據之間變化。

茉莉測試代碼是在這裏:

describe("Log Model", function() { 

    var mg = new MandellMVC(); 
    mg.setUseLocalData(true); 

    var log; 

    beforeEach(function() { 
     log = new Log(73936780); 
    }); 

    describe("function fetch", function() { 
     it("returns false if log type is invalid", function() { 
      expect(log.fetch(mg, function(){})).toBeFalsy(); 
     }); 

     // Not sure why this needs to be here too? 
     log = new Log(73936780); 
     log.setLogType('Proc'); 

     it("should make a real ajax request", function() { 
      var callback = jasmine.createSpy(); 
      log.fetch(mg, callback); 
      waitsFor(function() { 
       return callback.callCount > 0; 
      }); 
      runs(function() { 
       expect(callback).toHaveBeenCalled(); 
      }); 
     }); 
    }); 
}); 

第一測試通過。但後來第二個給出了錯誤timeout: timed out after 5000 msec waiting for something to happen。我試圖按照教程,但顯然不是很好。

謝謝你,任何幫助,非常感謝!

+1

什麼開發人員工具(或螢火蟲)說關於AJAX請求?它成功了嗎?另外,你應該在'describe'內部移動'beforeEach',因爲它只適用於一個級別(參見[docs](http://pivotal.github.io/jasmine/#section-Setup_and_Teardown)) – scriptin 2013-05-14 21:29:26

+0

'beforeEach'和'afterEach'級聯到嵌套描述就好了。請參閱您關聯的文檔中的下一部分 – Gregg 2014-02-08 22:07:42

回答

1

我覺得你的log = new Log(73936780)

聲明混合了正確的代碼應該是

describe("Log Model", function() { 
    var mg; 
    var log; 

    beforeEach(function() { 
     mg = new MandellMVC(); 
     mg.setUseLocalData(true); 

     log = new Log(73936780); 
     log.setLogType('Proc'); 
    }); 

    afterEach(function() { 
     delete mg; 
     delete log; 
    }); 

    describe("function fetch", function() { 
     it("returns false if log type is invalid", function() { 
      expect(log.fetch(mg, function(){})).toBeFalsy(); 
     }); 

     it("should make a real ajax request", function() { 
      var callback = jasmine.createSpy(); 
      log.fetch(mg, callback); 
      waitsFor(function() { 
       return callback.callCount > 0; 
      }); 
      runs(function() { 
       expect(callback).toHaveBeenCalled(); 
      }); 
     }); 
    }); 
}); 

此外,您也應該檢查的螢火,如果請求被髮送和響應被正確接收