[英]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"}
。
我想测试两个分支都起作用,即使用正确的参数正确调用了failureFunction
和successFunction
。
到目前为止,这是我的茉莉花:
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
可以称之为......但这似乎我的权利?
问题是它中的期望在我模拟的异步函数完成解析之前it
已经运行了。 因此,解决方案是将期望本身包装在类似的.then
。 这工作:
it("should call successsFunction appropriately", function(){
response.then(function() {
expect(window.successFunction).toHaveBeenCalledWith("asdf")
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.