Skip to main content

Integration testing guide

email testing

MailSlurp was designed with QA and integration testing in mind. There are SDKs for many languages and plugins for common test frameworks such as Cypress, Selenium, and Playwright. You can also find a wide array of example test projects on GitHub.

Examples

Loading examples...

Key features

MailSlurp is a complete email and SMS testing solution. You can create phone numbers and email accounts on demand during automated tests and use them to test email and SMS related processes in your applications. There are SDK packages published for many test frameworks and methods that enable the following features:

  • Create email addresses and phone numbers on demand
  • Wait for emails and SMS to arrive in tests
  • Extract links and verification codes from emails
  • Test authentication and sign up flows
  • Validate emails for spam and viruses
  • Trap outbound email with fake SMTP servers

How it works

MailSlurp is perfect for testing. You can create clean inboxes and phone numbers for each test run (or reuse existing) and mimic real user behavior and messaging in your tests. This is especially useful for testing user authentication flows in E2E browser tests.

How email testing works

Use MailSlurp email accounts in your tests to create unlimited clean email addresses on demand. You can then send and receive emails and extract links and verification codes from them. Here is an example of how it works:

emails

How SMS testing works

Use MailSlurp real phone numbers to receive SMS TXT messages in code and tests. You can receive two-factor authentication codes via SMS and verify TXT content. Here is an example of how it works:

sms

Creating inboxes

You can create inboxes in the dashboard on in code. You can assign randomly allocated addresses or use a custom domain for full control over inbox addresses.

const inbox = await mailslurp.createInbox();
// { id: '123', emailAddress: '123@mailslurp.com' }

Throwaway/temporary inboxes

Use temporary or throwaway inboxes during tests to avoid test pollution and clean-up. You can create inboxes with a short lifespan and MailSlurp will delete them after they expire.

// create an inbox that expires in 5 minutes
const inbox2 = await mailslurp.createInboxWithOptions({
expiresIn: 5 * 60_000,
});

Receiving messages

Waiting for matching content

A key feature of MailSlurp is the ability to await expecting messages using the wait for methods. You can use wait methods to hold a connection open in tests until an expected email or SMS arrives. This is useful for testing asynchronous processes such as email verification and password resets so that tests are not flaky.

// wait for the latest unread sms
const [sms] = await mailslurp.waitController.waitForSms({
waitForSmsConditions: {
count: 1,
unreadOnly: true,
phoneNumberId: phoneNumber.id,
timeout: 30_000
}
});
// extract a code from body with regex
expect(sms.body).toContain('Your code: 123')
const [, code] = /.+:\s([0-9]{3})/.exec(sms.body)
expect(code).toEqual('123')

Receiving codes

MailSlurp is perfect for receiving codes. You can use a simple regular expression on a message body to extract a code. Here is an example of receiving a code from an email:

cy.then(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();
})
})

MailSlurp provide convenience functions for finding links in emails and SMS:

// extract the links using MailSlurp
const links = await mailslurp.emailController.getEmailLinks({
emailId: email.id,
});
browser.assert.equal(
links.links.length,
1,
"Expect to find 1 link in the email",
);
loginLink = links.links[0];

Query HTML

Extract HTML content from emails using CSS query type selectors:

// query HTML for content
const { lines } = await emailController.getEmailHTMLQuery({
emailId: emailId,
htmlSelector: '.heading > .username'
});

Testing email validity

You can also test emails themselves using MailSlurp. This means you can receive emails from your servers and make assertions about their rendering, content, images, links and spam ratings.

Verifying email content

You can visually test email content in the dashboard. This gives you details on email feature support across browsers.

Test email feature support in code

You can also check which features are support across different devices and platforms using the email feature check options.

const { result } = await mailslurp.emailController.checkEmailBodyFeatureSupport({
emailId: email.id
})
expect(result.detectedFeatures).toContain(EmailFeatureSupportResultDetectedFeaturesEnum.html_doctype)
expect(result.featurePercentages.find(it => it.status === EmailFeatureSupportStatusPercentageStatusEnum.SUPPORTED)?.percentage).toBeGreaterThan(50)

Test emails for broken links and 404s:

const result = await mailslurp.emailController.checkEmailBody({
emailId: email.id
})
expect(result.hasIssues).toEqual(true)
expect(result.linkIssues.length).toEqual(1)
expect(result.linkIssues[0].url).toEqual("https://api.mailslurp.com/not-existing")

Detect missing images

Test for missing images in emails:

Video example:

Next steps:

Cypress documentation

Jest

Testing in NodeJS is easy using the mailslurp-client

// get the verification code for a given inboxId
async function getVerificationCode(inboxId: string) {
const emails = await api.getEmails(inboxId, { minCount: 1 });
const latestEmail = await api.getEmail(emails[0].id);
const verificationCode = /code = (.*)/.exec(latestEmail.body)![1]!;
return verificationCode;
}
expect(await getVerificationCode(id)).toContain('123');

Video example:

Next steps:

Node documentation

Playwright

MailSlurp works natively with Playwright tests. Use it to create disposable mailboxes when running tests:

await page.click('[data-test="sign-up-create-account-button"]');
// wait for verification code
const sms = await mailslurp.waitController.waitForLatestSms({
waitForSingleSmsOptions: {
phoneNumberId: phone.id,
unreadOnly: true,
timeout: 30_000,
}
})
// extract the confirmation code (so we can confirm the user)
const code = /([0-9]{6})$/.exec(sms.body)?.[1]!!;

Video example:

Next steps:

Playwright documentation

Selenium

Integrate the MailSlurp Java, Python, or CSharp SDK with Selenium to test email and SMS in Java. See the example projects for more information.

/**
* Create a real email address with MailSlurp and use it to start sign-up on the playground
*/
@Test
public void test3_canCreateEmailAddressAndSignUp() throws ApiException {
logger.info("Create email address");
// create a real, randomized email address with MailSlurp to represent a user
InboxControllerApi inboxControllerApi = new InboxControllerApi(mailslurpClient);
inbox = inboxControllerApi.createInboxWithDefaults();

logger.info("Assert inbox exists");
// check the inbox was created
assertNotNull(inbox.getId());
assertTrue(inbox.getEmailAddress().contains("@mailslurp"));

logger.info("Fill elements");
// fill the playground app's sign-up form with the MailSlurp
// email address and a random password
driver.findElement(By.name("email")).sendKeys(inbox.getEmailAddress());
driver.findElement(By.name("password")).sendKeys(TEST_PASSWORD);

logger.info("Submit sign-up button");
// submit the form to trigger the playground's email confirmation process
// we will need to receive the confirmation email and extract a code
driver.findElement(By.cssSelector("[data-test=sign-up-create-account-button]")).click();
}

Video example:

Other frameworks

You can use MailSlurp with any test framework or library by integrating the MailSlurp SDKs or REST API with your test code. You can also use Postman or the MailSlurp dashboard to build tests in a visual manner.

Next steps:

Selenium documentation