Imagine the application opens your email client and sends a message. This is possible by opening a browser window with an email url, something like mailto:recipient?subject=...&body=...
In this blog post I will show how you can parse such url and confirm something in the text of the message.
🎁 You can find the tested example used in this blog post in the recipe "Parse Email URL" on my Cypress examples site.
Here is our application code. The app uses window.open
method to create a popup window. A typical browser would then prompt the user to send the pre-filled email.
1 | <button id="email">Share link</button> |
1 | document |
I have described how to deal with window.open
method call in my previous blog post Deal with Second Tab in Cypress. Let's do it:
1 | // prepare for the "window.open" to be called |
Notice how the parameters in the email url are URL-encoded by the URLSearchParams:
1 | mailto:recipient?subject=Use+this+promotion+code&body=Hello%2C+friend%0DHere+is+your+link+to+get+a |
Let's get this string from the window.open
Sinon stub
1 | cy.get('@open') |
We want the search parameters after the "?" character. Let's use browser API URLSearchParams to parse and escape:
1 | cy.get('@open') |
Let's find the shared url in the email body, which is at the last line. We can split the text and get the last line
1 | ... |
Tip: I like using a chain of commands, since they are so easy to debug. Just click on any command and see the details in the DevTools console. For example, what did invoke .split()
do? What did it split? What did it yield to the next command .at(-1)
? Let's click and find out!
Separate chains
The chain of commands is a little too long. We can split it up by saving intermediate subjects using Cypress aliases and write simpler code using cypress-map helpers.
Our test starts the same way and stores the email URL params in an alias
1 | cy.window().then((win) => { |
We now have the encoded URL search parameters in an alias params
. We can convert it to a plain object via URLSearchParams API.
1 | cy.get('@params') |
Get the email body and extract the HTTPS link. Imagine the link could be anywhere, so let's use a regular expression with a named capture group.
1 | cy.get('@email') |
Now we can validate the link or visit it. Let's confirm the text GLEB10OFF
is one of the path segments
1 | cy.get('@link') |
The test passes
Nice.