Robin Vysloužil
Robin Vysloužil

Reputation: 35

Get email in mailcatcher via cy.request

I'm trying to get email catched by Mailcatcher in Cypress test. Mailcatcher runs at localhost:1080, and my app is running on port 3000.

So far I cannot simply use cy.visit('localhost:1080) because I am already visiting my app via cy.visit() (second unique domain). So I tried this:

cy
.request('http://localhost:1080/')
.its('body') //this gives me only a list of headers

The email is stored inside <tbody></tbody>, but that request above shoves me, that the <tbody> element is empty

I'm expecting to get tr where email is stored. Any suggestions how to do that?

Upvotes: 1

Views: 1184

Answers (2)

andy
andy

Reputation: 21

I hit this exact scenario (testing with Cypress to make sure an email was successfully sent via Mailcatcher) and took the suggested approach of proxying requests.

I noticed that Mailcatcher includes a pretty rudimentary API which allows me to get a list of sent emails via the following URL:

http://localhost:1080/messages

I can then get specifics of each email with requests to (replace 1 with the ID of the Mailcatcher email):

  • http://localhost:1080/messages/1.json
  • http://localhost:1080/messages/1.plain
  • http://localhost:1080/messages/1.html

Thanks to this interface, a proxy is pretty easy. In my scenario, I used PHP for the proxy and my setup looks something like:

  1. Add a new page at http://localhost/mailcatcher_proxy.php
  2. Add code in mailcatcher_proxy.php to take the args from the request and use cURL to return a request to localhost:1080/messages/
  3. Format result and print it in mailcatcher_proxy.php so that it's easily testable via Cypress

Worked like a charm!

Upvotes: 2

Mr. J.
Mr. J.

Reputation: 3741

Not my solution, just borrowed it from google and the github of Cypress (https://github.com/cypress-io/cypress/issues/418):

Email does seem like a common scenario that would require an additional domain. The solution we went for was to use https://mailcatcher.me/ to make the emails available in the browser then add a proxy to webpack-dev-server so that it could be accessed on the same host as the webapp. That way you can treat the email as just another page, visit it and click the link. If you need to hit your backend server you can add an additional proxy to make that available on the webapp domain.

Upvotes: 0

Related Questions