{ expect(str).to.equal( "Please confirm you woul" /> { expect(str).to.equal( "Please confirm you woul" /> { expect(str).to.equal( "Please confirm you woul"/>

Handling multiple confirm windows cypress

231 Views Asked by At

My test contains two confirm popups. The first one is handled like so:

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;
});

So I am testing the text of the confirmation dialogue and clicking confirm by returning true. I then try to do the same for the second confirmation popup that contains different text like so:

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?"
    );
});

When I run the test, the first popup assertion passes correctly. The second assertion fails as it is still looking for the string from the first assertion. So it seems the first window:confirm function is still getting called even though the second one should be.

1

There are 1 best solutions below

0
Emerson On

One way to handle the problem is to make the listener a once() listener. The once() version will only handle one call to 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?"
  )
})

If you have more challenging sequence of popups, you can use a counter, and a single listener that catches all popups.

// 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
})