2016-12-05 73 views
0

我想測試以下組件的控制器查找功能:

lookup() { 
    if (this.index == 1) { 
     return $.get('http://www.stackoverflow.com').then(res => { 
      this.index = res.data; 
      return res; 
     }); 
    } 
} 

爲了測試它,這是什麼我做:

controller.lookup(); 

大多數時候,它只是在執行這條線

if (this.find.index == 1) { 
     return $.get('http://www.stackoverflow.com'); 
} 

,而不是執行.then(..)承諾。我猜,在一些運行期間,我得到了jquery「get」請求的響應,因此,「then」承諾被執行,但是有沒有辦法等到收到「get」響應或僞造的響應? (使用興農間諜嘗試,但至今沒有運氣)

感謝您的幫助!

回答

0

的推薦方法是嘲笑/間諜的API調用。你可以做這樣的事情,

sinon.stub($, 'get').returns({then: function(callback) { 
    callback({user: 'ABC'}); 
}}); 

這裏工作example

而不是使用手動回調,你可以使用的承諾。

+0

謝謝,這爲我工作。 – angTest9