簡體   English   中英

如何茉莉花測試異步功能

[英]How to Jasmine test an async function

我通常在異步方面很糟糕。 我已經閱讀了所有其他答案,但是它們並沒有幫助我理解這一點。 這是我要測試的代碼:

$("#do").click(function() {
  someFunction().then(function(result) {
    if (result.error) {
      failureFunction(result.error_message)
    } else {
      successFunction(result.token)
    }
  })
})

someFunction()是一個異步函數,將返回{error: true, error_message: "failed due to error"}{token:"success token"}

我想測試兩個分支都起作用,即使用正確的參數正確調用了failureFunctionsuccessFunction

到目前為止,這是我的茉莉花:

describe("calling someFunction", function() {
  describe("when result is good", function() {
    beforeEach(function() {
      spyOn(window, "successFunction")
      response = Promise.resolve({token: "asdf"});
      spyOn(window, "someFunction").and.returnValue(response)
      $("#do").trigger("click")
    })
    it("should call successsFunction appropriately", function(){
      expect(window.successFunction).toHaveBeenCalledWith("asdf")
    })
  })
  // ... once I get above to pass it's just emulating with failureFunction
})

運行時出現的錯誤:

TypeError: Cannot read property 'then' of undefined

所以我猜測,廢止returnValuesomeFunction (這是response )不在其承諾的對象.then可以稱之為......但這似乎我的權利?

問題是它中的期望在我模擬的異步函數完成解析之前it已經運行了。 因此,解決方案是將期望本身包裝在類似的.then 這工作:

it("should call successsFunction appropriately", function(){
  response.then(function() {
    expect(window.successFunction).toHaveBeenCalledWith("asdf")
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM