Cypress Email Plugin - Test email accounts in Javascript (and Typescript)
Use real email accounts in CypressJS to test user sign-up, email verification, and more.
Cypress is a powerful end-to-end browser testing framework for Javascript and Typescript. With the official MailSlurp Cypress plugin you can create real email addresses in code. Send and receive email in Cypress to test user authentication, password reset, MFA, newsletters and more.
In this example we will use MailSlurp and Cypress JS to test the sign-up process of a dummy app hosted at playground.mailslurp.com.
Example application
Our example app is a simple React SPA. It allows a user to sign up with an email address and password. After sign up an email verification code is sent to the user's email address. The code must be read and entered into the app to confirm the user. Once confirmed a user may login and see a picture of a happy dog.
Install Cypress and MailSlurp plugin
To use MailSlurp with Cypress first install the MailSlurp Cypress Plugin and CypressJS.
npm install --save-dev cypress cypress-mailslurp
If you wish to write tests using the standard MailSlurp client install mailslurp-client
instead.
Initialize Cypress directories
To generate test directories in your project run:
cypress open
A tree of directories will be created under a cypress folder
. Edit yours to look like this:
cypress
├── fixtures
├── integration
│ └── integration-test.spec.ts
├── plugins
├── screenshots
├── support
│ ├── commands.js
│ └── index.js
└── videos
Import the MailSlurp plugin
Include the MailSlurp plugin in your cypress/support/index.{js,ts}
file.
import "cypress-mailslurp";
Typescript support
If you wish to use Typescript run:
npm install --save-dev typescript
tsc --init
Then use reference comments in your tests to allow for MailSlurp type hints:
/// <reference types="cypress-mailslurp" />
Or define the type yourself like so:
import { MailSlurp } from "mailslurp-client";
declare global {
namespace Cypress {
interface Chainable {
mailslurp: () => Promise<MailSlurp>;
}
}
}
Setup API Key
The MailSlurp plugin expects a MailSlurp API Key. Create a MailSlurp account to get a free API Key.
Then set the CYPRESS_MAILSLURP_API_KEY
environment variable or use the cypress.json
file env
property:
Environment variable
CYPRESS_MAILSLURP_API_KEY=your-api-key cypress run
Cypress env property
{
"env": {
"MAILSLURP_API_KEY": "your-mailslurp-api-key"
}
}
Configure timeouts
For MailSlurp to send and receive emails set timeout values in cypress.json
:
{
"defaultCommandTimeout": 30000,
"responseTimeout": 30000,
"requestTimeout": 30000
}
Using the MailSlurp command
The MailSlurp Cypress plugin adds the mailslurp()
command to the global cy
object:
cy.mailslurp().then(mailslurp => /* use maislurp client methods here */)
This returns a promise that can be accessed using Cypress then
commands. The MailSlurp client passed to the then
methods is an instance of the standard mailslurp client. It has many methods for creating inboxes, sending emails, and receiving email content. Most methods are asynchronous.
Chaining then commands
MailSlurp methods are async so you can chain commands and access the results using Cypress then
methods.
cy.mailslurp()
.then(mailslurp => mailslurp.createInbox())
.then(inbox => {
expect(inbox.emailAddress).to.contain("@mailslurp")
})
Sharing variables across tests
You can also store variables like inboxes and emails between tests using Cypress wrap
and as
methods.
cy.mailslurp()
.then(mailslurp => mailslurp.createInbox())
.then(inbox => {
// save inbox id and email address to this (make sure you use function and not arrow syntax)
cy.wrap(inbox.id).as('inboxId')
cy.wrap(inbox.emailAddress).as('emailAddress')
});
When accessing aliased variables that have been wrapped you must use function notation (dynamic scope) not arrow syntax (lexical scope) so that this
refers to a Cypress context.
- Good:
function() { this.myAlias }
- Bad:
() => { this.myAlias }
Access the stored variables using this
inside a function.
it("can access wrapped variable", function () {
expect(this.emailAddress).to.contain("@mailslurp");
});
Full example
Let's put the Cypress MailSlurp plugin to work on a real example. The demo application at playground.mailslurp.com allows a user to sign up with an email address and password. They then receive a confirmation code by email that must be entered to confirm the account. Next the user can sign in and see a happy dog. We will next each stage next.
Setup test
Create a test file at cypress/integration/integration-test.spec.ts
. (We will use Typescript but you can use Javascript if you prefer.)
/// <reference types="cypress-mailslurp" />
describe("user sign up test with mailslurp plugin", function () {
// we will add tests here
});
Create an email address before test run
We want to create a new email address for each test run. Use a before
block inside the describe function to do so:
// use cypress-mailslurp plugin to create an email address before test
before(function () {
return cy.mailslurp()
.then(mailslurp => mailslurp.createInbox())
.then(inbox => {
// save inbox id and email address to this (make sure you use function and not arrow syntax)
cy.wrap(inbox.id).as('inboxId')
cy.wrap(inbox.emailAddress).as('emailAddress')
})
});
Notice how we wrap the inbox id
and emailAddress
as separate aliases. We will use those in other test methods to sign up a user and receive a confirmation code.
Navigate to test application
Next we can load the playground application and assert the page title is shown.
it("01 - can load the demo application", function () {
// get wrapped email address and assert contains a mailslurp email address
expect(this.emailAddress).to.contain("@mailslurp");
// visit the demo application
cy.visit("https://playground.mailslurp.com")
cy.title().should('contain', 'React App');
});
Sign up a user
Now we fill out the sign-up form using our created email address and a test password. Notice how we access the wrapped variables using this
.
it("02 - can sign up using email address", function () {
// click sign up and fill out the form
cy.get("[data-test=sign-in-create-account-link]").click()
// use the email address and a test password
cy.get("[name=email]").type(this.emailAddress).trigger('change');
cy.get("[name=password]").type('test-password').trigger('change');
// click the submit button
cy.get("[data-test=sign-up-create-account-button]").click();
});
Cypress submits the form and the playground app will send our user a confirmation email.
In the next step we will wait for the email to be received and then extract the code from the body.
Receive emails with Cypress
MailSlurp inboxes have real email addresses. We can use the waitFor
methods to receive emails for a given inbox. In this test we wait for an email to arrive at the inbox we created and then use a regular expression to extract the confirmation code.
it("03 - can receive confirmation code by email", function () {
// app will send user an email containing a code, use mailslurp to wait for the latest email
cy.mailslurp()
// use inbox id and a timeout of 30 seconds
.then(mailslurp => mailslurp.waitForLatestEmail(this.inboxId, 30000, true))
// extract the confirmation code from the email body
.then(email => /.*verification code is (\d{6}).*/.exec(email.body!!)!![1])
// fill out the confirmation form and submit
.then(code => {
cy.get("[name=code]").type(code).trigger('change');
cy.get("[data-test=confirm-sign-up-confirm-button]").click();
})
});
Lastly we submit the code to the confirmation form.
Sign in with confirmed account
Now that our user has confirmed their account we can sign in and see a welcome message.
The code to sign in and test the welcome message looks like this:
// fill out sign in form
it("04 - can sign in with confirmed account", function () {
// use the email address and a test password
cy.get("[data-test=username-input]").type(this.emailAddress).trigger('change');
cy.get("[data-test=sign-in-password-input]").type('test-password').trigger('change');
// click the submit button
cy.get("[data-test=sign-in-sign-in-button]").click();
});
// can see authorized welcome screen
it("05 - can see welcome screen", function () {
// click sign up and fill out the form
cy.get("h1").should("contain", "Welcome");
});
If successful we should see a welcoming dog.
Building your own commands
If you want to create your own Cypress commands that use MailSlurp then install the default MailSlurp client:
npm install --save mailslurp-client
Then add your own commands to cypress/support/commands.js
:
const { MailSlurp } = require("mailslurp-client");
const apiKey = "YOUR_MAILSLURP_API_KEY";
const mailslurp = new MailSlurp({ apiKey });
For instance you can create your own createInbox
or waitForLatestEmail
commands:
Cypress.Commands.add("createInbox", () => {
return mailslurp.createInbox();
});
Cypress.Commands.add("waitForLatestEmail", (inboxId) => {
return mailslurp.waitForLatestEmail(inboxId);
});
Now in Cypress tests we can do the following:
cy.createInbox().then((inbox) => {
console.log(inbox);
// { id: '...', emailAddress: '...' }
});
Or
cy.waitForLatestEmail(inbox.id).then((email) => {
console.log(email);
// { subject: '...', body: '...' }
});
Conclusion and next steps
Cypress is a great way to test applications end to end. You can use the Cypress MailSlurp plugin to create real email addresses during tests. Use it to send and receive emails and attachments in Cypress while testing user sign-up, login, and more. For more help see the MailSlurp examples pages or the developer documentation.
As always, example code is available on GitHub.
Related content
Golang email library
Golang Email Library for sending and receiving emails in Go over SMTP or HTTP/S.
Javascript email libraries for MailSlurp
Nodemailer alternatives to send and receieve email in code and tests
MailSlurp Zapier Email Plugin
Create email accounts to send and receive emails and attachments as Zapier actions and triggers.
Email for testing
Test email accounts for email testing. Alternatives to Mailinator, MailTrap, Mailosaur and more.
How to wait for Selenium to start during Codeception tests
Example tutorial for how to wait until webdriver and Selenium have started during Codeception PHP tests
Email API for email marketing and more
APIs for email marketing and social campaign testing. Send, receive, validate and test emails in code and online.
Fastest way to start a typescript project
Modern typescript tooling has come a long way. See how to setup a new project with TS-Node, TSC, and typeconfig.json.
Fetch error message javascript
Handle response exceptions with Fetch in Javascript
GraphQL API disposable email accounts
How to create real email addresses using GraphQL to send and receive emails in tests and frontend applications.
GraphQL Email API Tutorial
Did you know you can send and receive emails using GraphQL?
How to test an email address
Test email accounts for testing email addresses in code or online. Create fake email accounts for testing.
Hugo responsive image srcsets
Serve responsive picture tags with custom render-image layout partial in Hugo static site generator.
NodeMailer NPM Tutorial
Send and receive email using NodeMailer in Node JS.
How to start selenium in a background process and wait for i...
Spawn Selenium server process before tests start for easier acceptance testing.
Create custom print classes with Tailwind
Configure tailwind.config.js to create prefixed classes with a custom media query.
Send and receive email in Cypress JS tests with MailSlurp
Test email sign-up. password verification and more with Cypress JS and MailSlurp.
Cypress Email Plugin - Test email accounts in Javascript (an...
Use real email accounts in CypressJS to test user sign-up, email verification, and more.
Golang mail Library (SMTP)
How to send and receive emails in Go (test email addresses).
Email APIs for Java and Kotlin projects
Test email sending and receive emails without a mail server.
Java TestNG Selenium user sign up testing with real email ad...
Testing user sign up in Java using TestNG and MailSlurp test email accounts
Codeception PHP acceptance testing using real email address ...
Write acceptance tests in PHP with real email addresses using Codeception and MailSlurp
PHP Email Test Plugins: send and receive email in PHPUnit (e...
How to send and receive emails in PHPUnit tests.
PyTest email testing
Send and receive email in Pytest Python tests.
Selenium test email plugins: send and receive email in tests...
Receive emails in Java test suites using MailSlurp, Junit, and Selenium.
Receive email in PHP: using MailSlurp to send and receive em...
Test email in PHP using real email addresses
Robotframework Python Testing using real email addresses
Python automation email testing Robotframework plugin
Testing authentication using real email addresses in Ruby wi...
Cucumber example project using Capybara to test user authentication using real email addresses.
Send email with Axios JS (and receive email too!)
Send email in Javascript with MailSlurp email API
Test applications with real emails using Serenity BDD, JBeha...
Email acceptance testing with Serenity and MailSlurp. Test applications with real email addresses.
.NET SpecFlow testing using MailSlurp email accounts and Sel...
How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.
Test email accounts with Jest and Puppeteer
Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.
Test Emails in Selenium with DotNet, CSharp and MailSlurp
Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.
Test emails with Cucumber and Ruby
Generate test email accounts with Ruby and Cucumber. Test email sign-up, password verification and more.
Test user sign-up with NodeJS and WebDriver
Test email related processes like sign-up and verification using WDIO WebDriver and MailSlurp.
TestCafe end-to-end MFA testing for user sign-up and email v...
End-to-end testing with MailSlurp, NodeJS, and TestCafe.
Base64 file uploads
How to encode files as Base 64 encoded strings in several languages
Deno Email Apis
Send and receive emails in Deno JS. Use APIs in Deno with MailSlurp.
Email read (opened seen settings)
How to control the seen or read settings for an email using MailSlurp.
How To Test Emails Before You Send
There are many free tools to test emails before sending. This can help prevent spam warnings and increase deliverability...
GraphQL Email API
Fetch and read emails with GraphQL inboxes using MailSlurp email API.
Testing OTP password link username and password for 2 factor...
Testing OTP password link username and password for 2 factor authentication (2FA)
MailSlurp NodeMailer SMTP Usage
Use SMTP nodemailer with MailSlurp disposable email addresses
Test email address
Free test email address for testing emails online with web dashboard or REST API.
Testing email-related functionality with MailSlurp
Use MailSlurp to test email related functionality using real email addresses.
Testing email with Cypress test email accounts
Test email accounts for CypressJS. End-to-end testing with real email addresses using MailSlurp Cypress plugin.
Testing Webhooks
How to test HTTP webhooks using MailSlurp test hooks.
Send emails in NodeJS using SMTP
How to use Javascript SMTP client (or Nodemailer) to send email with MailSlurp mail server
Testing Email with Cypress JS and MailSlurp
Email testing with Cypress JS