ItsNotAndy
ItsNotAndy

Reputation: 573

How to paste from clipboard in cypress

I am using cypress to test the flow of my application. At this point it just opens an account and follows the flow as a user would. At a point I copy a link and would like to follow that link.

The issue I have is that the link changes with every test that I run and I don't know what the link is until its been copied. When the test finishes, I would like to paste that link in the browser and make sure that the page does exist.

I cant seem to find a way to paste from my clipboard. Is there a way to do this ? My next test basically needs to start with

cy.visit('paste');

Ive tried doing

cy.visit('{Ctrlv}');

But that does not seem to work.

Upvotes: 2

Views: 5234

Answers (1)

user16695029
user16695029

Reputation: 4440

I think what you want to do is use cy.request() to test the link exist.

cy.visit(pasted-link-here) might be tricky if the link you need to test is outside the original domain, but cy.request() can give you a status code.

cy.window().then(win => {
  win.navigator.clipboard.readText().then(urlFromClipboard => {
    cy.request(urlFromClipboard)
      .then(response => expect(response.status).to.eq(200))
  })
})

Actually, see here

cy.request() requires that the response status code be 2xx or 3xx

so you could just use this

cy.window().then(win => {
  win.navigator.clipboard.readText().then(urlFromClipboard => {
    cy.request(urlFromClipboard)
  })
})

and the test will fail if status code is a failure code.

Upvotes: 6

Related Questions