I'm struggling with waiting for async functions to finish. In particular, I found these two methods to wait for completion of an async function before the test continues but don't know the difference (if there is one):
我在等待异步功能完成时苦苦挣扎。特别是,我发现这两种方法在测试继续之前等待异步函数完成,但不知道其中的区别(如果有区别的话):
cy.then(() => myAsyncFunction())
cy.wrap(null).then(() => myAsyncFunction())
My goal is to wait for two async functions in the beforeEach()
block before the actual tests start:
我的目标是在实际测试开始之前,在beforeEach()块中等待两个JavaScript函数:
beforeEach(() => {
myAsyncFunction1() // This function has to be completed before the next one starts
myAsyncFunction2() // This function has to be completed before the test continues
// Only when myAsyncFunction2() has completed the actual tests should start
});
I tried to Google for the difference and took a look in the documentation for Cypress but sadly didn't find an answer for how this behaves.
我试着在谷歌上寻找不同之处,并在Cypress的文档中看了看,但遗憾的是没有找到这是如何表现的答案。
更多回答
Why not just write an async hook and await them? You're not actually trying to interleave this with any Cypress commands.
为什么不直接编写一个异步钩子并等待它们呢?您并不是真的想把它与任何Cypress命令交织在一起。
优秀答案推荐
There is no difference between the two calls. cy.then()
is an undocumented shorter form of cy.wrap(something).then()
.
这两种呼叫之间没有区别。cy.then()是cy.wrap(something).then()的一种未记录的较短形式。
cy.then()
will not wait for asynchronous functions to finish in the way you are asking.
那么()将不会按照您所要求的方式等待异步函数完成。
If you want myAsyncFunction2()
to wait for myAsyncFunction1()
, you would use normal javascript patterns - but it depends entirely on what is inside those functions.
如果您希望myAsyncFunction2()等待myAsyncFunction1(),您可以使用普通的Java脚本模式--但这完全取决于这些函数中的内容。
cy.then()
is useful to wait for the command queue to finish, particularly when the commands modify a closure variable.
在等待命令队列完成时,cy.Then()非常有用,尤其是当命令修改闭包变量时。
let result;
cy.get(selector).then($el => result = $el.text())
cy.then(() => {
cy.log(result) // logs the element text
})
Cypress prefers not to use closure variables, since many people have trouble understanding why the value isn't updated in sequence. Instead they provide an alias
feature to handle asynchronous variables.
Cypress不喜欢使用闭包变量,因为许多人很难理解为什么值没有按顺序更新。相反,它们提供了一个别名功能来处理异步变量。
Please read Variables and aliases for more info.
有关更多信息,请阅读变量和别名。
Waiting for the asynchronous functions
As long as myAsyncFunction*()
returns a promise, you just need to return that promise from beforeEach()
.
只要myAsyncFunction*()返回承诺,您只需要从bepreEach()返回该承诺。
Cypress always waits for returned promises to complete before moving to the next command.
赛普拉斯总是等待退回的承诺完成,然后再转到下一个指挥部。
beforeEach(() => {
return myAsyncFunction1().then(() => {
return myAsyncFunction2() // promise returned here will be awaited
})
})
更多回答
我是一名优秀的程序员,十分优秀!