2013-02-28 185 views
17

我越來越茉莉(http://pivotal.github.com/jasmine/)熟悉內部不上班,發現莫名其妙的東西:jasmine.js期待()異步回調

it("should be able to send a Ghost Request", function() { 
    var api = fm.api_wrapper; 

    api.sendGhostRequest(function(response) { 
    console.dir('server says: ', response); 
    }); 

    expect(true).toEqual(false); 
}); 

未能如預期。

然而,在移動期望回調內撥打:

it("should be able to send a Ghost Request", function() { 
    var api = fm.api_wrapper; 

    api.sendGhostRequest(function(response) { 
    console.dir('server says: ', response); 
    expect(true).toEqual(false); 
    }); 
}); 

不知何故傳遞:o

一些調試之後: api.sendGhostRequest()執行一個異步AJAX請求,和茉莉燈心草過去之前請求已完成。

因此,問題:

如何獲得茉莉花確定測試結果之前等待AJAX​​執行?

+1

茉莉花2.0,你只需要調用它( 「降序」,函數(done){... done(); ...})。只是說,因爲這個線程是在谷歌結果高:) – pkopac 2016-04-12 13:33:31

回答

12

編輯茉莉2

異步測試已經成爲茉莉花2.任何測試需要處理異步代碼可以用一個回調,這將顯示測試的完成寫簡單得多。見頭異步支持下Jasmine 2 docs

it('should be able to send a ghost request', (done) => { 
    api.sendGhostRequest((response) => { 
     console.log(`Server says ${response}`); 
     expect(true).toEqual(false); 
     done(); 
    }); 
}); 

茉莉花1

有頭異步支持下的Jasmine site看看waitsFor()運行()

使用runs和waitsfor應強制Jasmine等待ajax調用完成或暫停。

的代碼是這樣:

it("should be able to send a Ghost Request", function() { 
    runs(function() { 
     api.sendGhostRequest(function(response) { 
      console.dir('server says: ', response); 
      flag = true; 
     }); 
    }, 500); 

    waitsFor(function() { 
     return flag; 
    }, "Flag should be set", 750); 

    runs(function() { 
     expect(true).toEqual(false); 
    }); 
} 

在這種情況下,期望將失敗。

+0

乾杯!感到尷尬,就像我剛剛RTFM編輯:)作品像一個魅力:) – 2013-02-28 17:47:42

+0

什麼是'500'在第一次運行()結束? – zkent 2014-01-08 17:26:16

+0

第一次運行時的500是異步操作的超時。或者,您可以在api.sendGhostRequest調用之後添加一個setTimeout,以提供在超時時執行的備用案例。例如: setTimeout(function(){ flag = true; },500); – halfs13 2014-01-14 18:50:24

1

查找到運行()和WAITFOR()

具體來說,你可以打電話給WAITFOR確認回調已經以某種方式運行(可能使用一個布爾值作爲檢查?),然後運行事後期待。

運行允許您等待waitfor完成。

async jasmine documentation

+0

謝謝!應該閱讀手冊.. – 2013-02-28 17:46:31

4

由於@pkopac評論,runs()waitsFor()已經在使用done()回調V2贊成被棄用記載:https://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

it("should be able to send a Ghost Request", function(done) { 
    var api = fm.api_wrapper; 

    var success = function(response) { 
     console.dir('server says: ', response); 
     expect(response).toEqual('test response') 
     done(); 
    }; 

    api.sendGhostRequest(success); 
}); 
+0

'done'應該在函數參數中使用。 (「應該可以發送Ghost請求」,函數(done){' – 2017-08-18 07:28:33

+0

good catch!謝謝@Chase Choi! – ptim 2017-08-20 10:51:47

+0

如何等待條件在規範中變爲真?我該怎麼做,如果我想要等待我的應用程序工作,但我沒有「成功」回調?我是否需要編寫自己的「waitFor」輪詢循環? – Rich 2017-09-25 10:22:19