如何茉莉花测试异步功能

时间:2018-11-29 06:42:00

标签: javascript jquery asynchronous jasmine

我通常对异步感到很恐惧。我已经阅读了所有其他答案,但是它们并没有帮助我理解这一点。这是我要测试的代码:

$("#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

因此,我猜测returnValue的存根someFunction(即response)不是可以在其上调用.then的promise对象...但是对我来说这合适吗?

1 个答案:

答案 0 :(得分:0)

问题是it中的期望在我模拟的异步函数完成解析之前就已运行。因此,解决方案是将期望本身包装在类似的.then中。这可行:

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