Mailosaur logo
Mailosaur logo

How to test SMS messages with Cypress

Overview
A hashtag icon

Whether you want to check that a one-time passcode always arrives when you expect, or need to check the content of the account notifications you send to customers, you can use Mailosaur to automate SMS testing in Cypress. Mailosaur is a testing suite that lets you automate email testing with Cypress and other testing frameworks. This is important for websites and web apps that send an email (password resets, account setup, marketing emails, etc.). Mailosaur also lets you test SMS messages with Cypress too!

If you don’t already have one, you’ll need to create a free trial account. Once you’re in, just familiarize yourself with sending email into Mailosaur and you’ll be ready to start testing!

How to test SMS with Cypress
A hashtag icon

In order to start SMS testing with Cypress, just install the Mailosaur Cypress plugin and write your first test spec...

1. Install the Mailosaur Cypress plugin
A hashtag icon

Mailosaur provides an official set of custom commands, that allow you to automate SMS testing seamlessly in Cypress.

Extend Cypress, by installing Mailosaur’s custom commands package cypress-mailosaur.

Install via npm or yarn
A hashtag icon

cd your/project/path
npm i -D cypress-mailosaur
# or
yarn add -D cypress-mailosaur

Once installed, register the commands by appending an import statement to the cypress/support/e2e.js file (or cypress/support/index.js in older versions of Cypress), within your project folder:

echo "import 'cypress-mailosaur'" >> cypress/support/e2e.js

Authenticating with Mailosaur
A hashtag icon

In order to connect to Mailosaur, you need to add your API key to your tests. You access your API key via the account settings screen.

Add API key to cypress.config.js
A hashtag icon
module.exports = defineConfig({
  env: {
    MAILOSAUR_API_KEY: "your-key-here",
  },

  // ...
});
Alternatively, set API key via a system environment variable
A hashtag icon

To set the environment variable on your machine, it needs to be prefixed with either CYPRESS_ or cypress_.

export CYPRESS_MAILOSAUR_API_KEY=your-key-here

2. Write your test code
A hashtag icon

The code below connects to your Mailosaur account and finds any SMS messages sent to the phone number specified within the last hour, and asserts that the content contains what was expected.

cy.mailosaurGetMessage(serverId, {
  sentTo: '4412345666777' // Your Mailosaur phone number
}).then(message => {
  expect(message.text.body).to.contain('Hello world');
})

Narrowing your search results
A hashtag icon

Only find messages received after a certain time
A hashtag icon

By default, a search will include messages received in the last hour, but you can customise the search window with the receivedAfter option.

This example shows you how to only include emails received after your test started:

const testStart = new Date()

// Perform the steps that send a message here

cy.mailosaurGetMessage('SERVER_ID', {
  sentTo: '...'
}, {
  receivedAfter: testStart
}).then(message => {
  cy.log(message.text.body)
})
Search criteria
A hashtag icon

As you can see in the examples so far, you can search for the email address or phone number a message was sent to, but you can also search using this criteria too:

PARAMETER DESCRIPTION
sentFrom The full email address from which the target message was sent.
sentTo The full email address to which the target message was sent.
subject Find emails where the subject line contains this text.
body Finds messages where the message body contains this text.

Email not found in time?
A hashtag icon

By default, the mailosaurGetMessage command only looks for emails that were received by Mailosaur within the last hour.

You can override this by setting receivedAfter, like so:

cy.mailosaurGetMessage(serverId, {
  sentTo: testEmail
}, {
  // Find messages received since Jan 1st 2020. This will be slow!
  receivedAfter: new Date('2020-01-01T00:00:00Z')
})

Common test cases
A hashtag icon

Now that you have a working project that fetches an email, you can use this to begin writing tests for various pieces of functionality.

Check out these guides on the most common test cases:

Library reference
A hashtag icon

Messages
A hashtag icon

Messages is the collective name given to the email and/or SMS messages that are sent into Mailosaur for testing. The message object contains everything you need to perform in-depth automated testing.

cy.mailosaurGetMessage(server, criteria, options)
A hashtag icon

Waits for a message to be found. Returns as soon as a message matching the specified search criteria is found.

Recommended: This is the most efficient method of looking up a message, therefore we recommend using it wherever possible.

cy.mailosaurGetMessage('SERVER_ID', {
  sentTo: 'someone@SERVER_ID.mailosaur.net'
}).then((message) => {
  cy.log('Message subject:', message.subject);
});

To learn about Server IDs, and what to replace SERVER_ID with, see sending email to Mailosaur.

Criteria
A hashtag icon
PARAMETER DESCRIPTION
sentFrom The full email address from which the target message was sent.
sentTo The full email address to which the target message was sent.
subject The subject line of the target email.
body Search for part of the message body.
match If set to ALL (default), then only results that match all specified criteria will be returned. If set to ANY, results that match any of the specified criteria will be returned.
Options
A hashtag icon
PARAMETER DESCRIPTION
timeout Specify how long to wait for a matching result (in milliseconds, default value is 10 seconds).
receivedAfter Limits results to only messages received after this date/time (default 1 hour ago).
cy.mailosaurGetMessage('SERVER_ID', {
  sentTo: 'someone@SERVER_ID.mailosaur.net'
}, {
  // Search all messages received after midnight 5th Feb 2020
  receivedAfter: new Date(2020, 1, 5)
});

cy.mailosaurListMessages(server, options)
A hashtag icon

Returns a list of your messages in summary form. The summaries are returned sorted by received date, with the most recently-received messages appearing first.

Message summaries The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call mailosaurGetMessageById. Alternatively, we recommend using the mailosaurGetMessage method, which is a far more efficient approach.

// List the most recent messages
cy.mailosaurListMessages('SERVER_ID').then((result) => {
  // Get the most recent message (the first one in the list)
  const message = result.items[0];

  cy.log('Subject:', message.subject);
});
Options
A hashtag icon
  • receivedAfter Allows you to customise how far back to look for messages.
  • page Used alongside itemsPerPage to paginate through results. This is zero-based, meaning 0 is the first page of results.
  • itemsPerPage A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50.
  • dir Optionally limits results based on the direction (Sent or Received), with the default being Received.
// List all results received after midnight on 3rd Feb 2020
cy.mailosaurListMessages('SERVER_ID', {
  page: 0,
  itemsPerPage: 10,
  receivedAfter: new Date(2020, 1, 3)
});

cy.mailosaurSearchMessages(server, criteria, options)
A hashtag icon

Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first.

Message summaries The method returns a message summary, rather than the full message object. This means that several properties, like the message body, are not included. To get this data, you’ll need to call mailosaurGetMessageById. Alternatively, we recommend using the mailosaurGetMessage method, which is a far more efficient approach.

cy.mailosaurSearchMessages('SERVER_ID', {
  sentTo: 'someone@SERVER_ID.mailosaur.net'
}).then((result) => {
  // Get the most recent match
  const message = result.items[0];

  cy.log('Subject:', message.subject);
});
Criteria
A hashtag icon
PARAMETER DESCRIPTION
sentFrom The full email address from which the target message was sent.
sentTo The full email address to which the target message was sent.
subject The subject line of the target email.
body Search for part of the message body.
match If set to ALL (default), then only results that match all specified criteria will be returned. If set to ANY, results that match any of the specified criteria will be returned.
Options
A hashtag icon
PARAMETER DESCRIPTION
timeout If provided, determines how long to wait for a matching result (provided in milliseconds).
errorOnTimeout When set to false, an error will not be throw if timeout is reached (default: true).
receivedAfter Allows you to customise how far back to look for messages.
page Used alongside itemsPerPage to paginate through results. This is zero-based, meaning 0 is the first page of results.
itemsPerPage A limit on the number of results to be returned. This can be set between 1 to 1000, with the default being 50.
dir Optionally limits results based on the direction (Sent or Received), with the default being Received.
// Search for all messages sent to someone@SERVER_ID.mailosaur.net,
// received after midnight on 3rd Feb 2020. Limit results to
// the first 10 matches only.
cy.mailosaurSearchMessages('SERVER_ID', {
  sentTo: 'someone@SERVER_ID.mailosaur.net'
}, {
  page: 0,
  itemsPerPage: 10,
  receivedAfter: new Date(2020, 1, 3)
});

cy.mailosaurGetMessagesBySubject(server, subject)
A hashtag icon

Shorthand for a mailosaurSearchMessages query on message subject. Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first.

cy.mailosaurGetMessagesBySubject('SERVER_ID', 'Password reset');

cy.mailosaurGetMessagesBySentFrom(server, emailAddress)
A hashtag icon

Shorthand for a mailosaurSearchMessages query on message sender. Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first.

cy.mailosaurGetMessagesBySentFrom('SERVER_ID', 'someone@SERVER_ID.mailosaur.net');

cy.mailosaurGetMessagesBySentTo(server, emailAddress)
A hashtag icon

Shorthand for a mailosaurSearchMessages query on message recipient. Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first.

cy.mailosaurGetMessagesBySentTo('SERVER_ID', 'someone@SERVER_ID.mailosaur.net');

cy.mailosaurGetMessagesByBody(server, text)
A hashtag icon

Shorthand for a mailosaurSearchMessages query on message body. Returns a list of messages matching the specified search criteria, in summary form. The messages are returned sorted by received date, with the most recently-received messages appearing first.

cy.mailosaurGetMessagesBySubject('SERVER_ID', 'Hey there');

cy.mailosaurGetMessageById(id)
A hashtag icon

Retrieves the detail for a single email message. Must be used in conjunction with either mailosaurListMessages or mailosaurSearchMessages in order to get the unique identifier for the required message. We always recommend using the mailosaurGetMessage method instead.

cy.mailosaurListMessages('SERVER_ID').then((result) => {
  const messageId = result.items[0].id;

  cy.mailosaurGetMessageById(messageId).then((message) => {
    cy.log('Subject:', message.subject);
  });
});

cy.mailosaurDeleteMessage(id)
A hashtag icon

Permanently deletes a message. Also deletes any attachments related to the message. This operation cannot be undone.

cy.mailosaurDeleteMessage(messageId)

cy.mailosaurDeleteAllMessages(server)
A hashtag icon

Permanently deletes all messages held by the specified server. Also deletes any attachments related to each message. This operation cannot be undone.

cy.mailosaurDeleteAllMessages('SERVER_ID')

cy.mailosaurCreateMessage(server, messageCreateOptions)
A hashtag icon

Creates a new message that can be sent to a verified email address. This is useful in scenarios where you want an email to trigger a workflow in your product.

cy.mailosaurCreateMessage('SERVER_ID', {
  to: 'verified-address@example.com',
  send: true,
  subject: 'Request',
  text: 'Please can you give us a call back?'
});
Options
A hashtag icon
  • to The email address to which the email will be sent. Must be a verified email address.
  • send If true, email will be sent upon creation.
  • subject The email subject line.
  • text The plain text body of the email.
  • html The HTML body of the email.

cy.mailosaurForwardMessage(messageId, messageForwardOptions)
A hashtag icon

Forwards the specified email to a verified email address.

cy.mailosaurForwardMessage('MESSAGE_ID', {
  to: 'verified-address@example.com',
  text: 'FYI'
});
Options
A hashtag icon
  • to The email address to which the email will be sent. Must be a verified email address.
  • text Any additional HTML content to forward the email with.
  • html Any additional plain text content to forward the email with.

cy.mailosaurReplyToMessage(messageId, messageReplyOptions)
A hashtag icon

Sends a reply to the specified email. This is useful for when simulating a user replying to one of your emails.

cy.mailosaurReplyToMessage('MESSAGE_ID', {
  text: 'FYI'
});
Options
A hashtag icon
  • text Any additional plain text content to include in the reply.
  • html Any additional HTML content to include in the reply.

Servers
A hashtag icon

Servers contain all the configuration and set up for.

cy.mailosaurListServers()
A hashtag icon

Returns a list of your virtual servers. Servers are returned sorted in alphabetical order.

cy.mailosaurListServers().then((result) => {
  cy.log('You have a server called:', result.items[0].name);
});

cy.mailosaurCreateServer(server)
A hashtag icon

Creates a new virtual server. Only the name property is required to create a new server via the API.

cy.mailosaurCreateServer({
  name: 'My email tests'
});

cy.mailosaurGetServer(id)
A hashtag icon

Retrieves the detail for a single server. Simply supply the unique identifier for the required server.

cy.mailosaurGetServer('SERVER_ID').then((server) => {
  cy.log(server.name);
});

cy.mailosaurGetServerPassword(id)
A hashtag icon

Retrieves the password, for use with SMTP and POP3, for a single server. Simply supply the unique identifier for the required server.

cy.mailosaurGetServerPassword('SERVER_ID').then((password) => {
  cy.log(password);
});

cy.mailosaurUpdateServer(server)
A hashtag icon

Updates a single server.

retrievedServer.name = 'Updated server name';

cy.mailosaurUpdateServer(retrievedServer);

cy.mailosaurDeleteServer(id)
A hashtag icon

Permanently deletes a server. Also deletes all messages and associated attachments within the server. This operation cannot be undone.

cy.mailosaurDeleteServer('SERVER_ID');

cy.mailosaurGenerateEmailAddress(id)
A hashtag icon

Utility method to help you generate a random email address for a given server.

cy.mailosaurGenerateEmailAddress('SERVER_ID').then((emailAddress) => {
  cy.log(emailAddress); // "bgwqj@SERVER_ID.mailosaur.net"
});

To learn about Server IDs, and what to replace SERVER_ID with, see sending email to Mailosaur.

Files
A hashtag icon

cy.mailosaurDownloadMessage(messageId)
A hashtag icon

Downloads an EML file representing the specified email. Simply supply the unique identifier for the required email.

cy.mailosaurDownloadAttachment(attachmentId)
A hashtag icon

Downloads a single attachment. Simply supply the unique identifier for the required attachment.

Analysis
A hashtag icon

cy.mailosaurGetSpamAnalysis(messageId)
A hashtag icon

Perform spam testing on the specified email.

Cypress Blogs
A hashtag icon

What is Cypress? Getting started with Cypress

Previous