How can I get the stored value of a variable into a URL command using Cypress?

Viewed 1037

I am trying to write an end-to-end test using Cypress and mailslurp. I can retrieve activation URL from the onboarding email and have stored the value in a variable called verificationLink. Now that I have the URL, I want to use it in cy.visit(URL) but I don't know how to get the stored value out of the verificationLink.

I know the following code is incorrect, but it gives you the idea of what I am trying to do.

cy.waitForLatestEmail('inbox.id').then(email => {
  console.log(email)

  const verificationLink = /my-regex-code-to-get-the-link,e.g. \/([0-9]{6})$\//.exec(email.body);
  console.log(verificationLink)
  cy.visit(verificationLink)
})

I have tried to follow the instructions/advice from the links below but with no success. Does anyone know how to do this?

https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Closures

Grab a string to use in a .visit() call in cypress

1 Answers

We ended up writing our own mini-application to handle this case but the same idea could be leveraged for mailSlurp.

cy.latestEmail(inboxState).then((body) => {
                console.log(`Body is ${JSON.stringify(body)}`) //Transform the body of the latest email into a JSON string.
             
                userEmail = body.email //Save the email of the user based on the "email" property in the JSON
                console.log(userEmail)
                //Match the verification link embedded in the email
                const verificationLink = /http(s?):\/\/(MY_URL_ADDRESS_HERE\/account\/verifySms\?key=(\w+)/gm.exec(userEmail.content) //where array content returned will include the entire HTML content of the email
                console.log(verificationLink) //verificationLink = the array
                assert.isTrue(verificationLink.length > 0, 'verification link not found')
                verificationURL = verificationLink[0]
                cy.log(verificationURL)

Related