繁体   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