处理多个确认窗口 cypress

Pau*_*ips 0 javascript confirm reactjs cypress

我的测试包含两个确认弹出窗口。第一个处理如下:

cy.on("window:confirm", str => {
    expect(str).to.equal(
    "Please confirm you would like to leave this space. You will no longer be a member of this space."
    );
    return true;
});
Run Code Online (Sandbox Code Playgroud)

因此,我正在测试确认对话框的文本,并通过返回 true 来单击确认。然后,我尝试对包含不同文本的第二个确认弹出窗口执行相同的操作,如下所示:

cy.on("window:confirm", str => {
    expect(str).to.equal(
    "This will archive the space and any content posted within it. Are you sure you wish to continue?"
    );
});
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,第一个弹出断言正确通过。第二个断言失败,因为它仍在寻找第一个断言中的字符串。所以看起来第一个 window:confirm 函数仍然被调用,尽管第二个应该被调用。

小智 5

解决这个问题的一种方法是让倾听者成为once()倾听者。该once()版本将仅处理对window:confirm.

cy.once("window:confirm", str => {
  expect(str).to.equal(
    "Please confirm you would like to leave this space. You will no longer be a member of this space."
  );
  return true
})

cy.once("window:confirm", str => {
  expect(str).to.equal(
    "This will archive the space and any content posted within it. Are you sure you wish to continue?"
  )
})
Run Code Online (Sandbox Code Playgroud)

如果您有更具挑战性的弹出窗口序列,则可以使用计数器和捕获所有弹出窗口的单个侦听器。

// Want to ensure this sequence of messages
const popups = [
  "Please confirm you would like to leave this space. You will no longer be a member of this space.",
  "This will archive the space and any content posted within it. Are you sure you wish to continue?"
]
let counter = 0
cy.on("window:confirm", str => {
  expect(str).to.equal(popups[counter++])
  return true
})
Run Code Online (Sandbox Code Playgroud)