Nenad R
Nenad R

Reputation: 11

Cypress click on link in mailhog body email

I need a help about testing mailhog with cypress.

I am trying to click on "Forgot password" link in email body, any advice how to do it?

Upvotes: 1

Views: 1140

Answers (4)

Daniel.D.Abraham
Daniel.D.Abraham

Reputation: 177

The method proposed by @VincentLarue is more complicated than needed, and has some bugs.

Check out this regex101.com.

<a href="mydomain/verify/fXxo4s_isP-mlm">Verify account</a>
const regex = /(\/verify\/.*)"/    

const url= content.match(regex)[1]
cy.visit(url)

But it is actually a fragile method, the better way is to parse the response body.

Upvotes: 2

Vincent Larue
Vincent Larue

Reputation: 11

In my case, parsing the body didn't work (I could not query my "a" tag). I used a regex to retrieve my link and then click it.

In the mail body, my link looked like :

<a href="mydomain/verify/fXxo4s_isP-mlm">Verify account</a>

But in the log of

cy.mhGetAllMails().mhFirst().mhGetBody().then(body => {cy.log(body)})

it was melted with randoms = and \r\n since it was not parsed...

Working solution for me was to extract that match with a pattern accepting those character then remove them. And finally rebuild the link to visit it:

cy.mhGetAllMails().mhFirst().mhGetBody().then(content => {
        let token = content.match('verify\/([A-Za-z0-9=~_\\r\\n-]+)<')[1];
        token = token.replace(/(\r\n|=)/gm, "");
        cy.visit('/verify/' + token);
    })

Maybe not the cleaner solution but I hope it can helps

Upvotes: 0

Fody
Fody

Reputation: 32138

You can parse the body string to get the link, but it would be messy.

Better to use a DOMParser

cy.mhGetAllMails().mhFirst().mhGetBody().then(body => {

  const parser = new DOMParser();
  const doc = parser.parseFromString(body, 'text/html')  // make a DOM 

  const anchor = doc.querySelector('a')                  // look for anchor tag
  const href = anchor.href                               // get the link

  cy.visit(href)                                         // visit the link
})

Notes

You can't click on the link directly with .click() since the DOM created above is not the live one attached to Cypress. But you should be able to cy.visit(href) which does the same thing.

The only problem I foresee is a cross-origin error - if you get that, use the cy.origin() command Ref.


Please see @Mr.PrasadJ question How to access new tab by clicking on "href" if you need more details on cy.origin() usage with email body.

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18601

Assuming you have an HTML-based web app, you can directly use the text to find and click the element.

cy.contains('Forgot password').click()

Upvotes: 0

Related Questions