Skip to content

Instantly share code, notes, and snippets.



Created Aug 3, 2018
What would you like to do?
CodeceptJS helper to check for emails in Mailcatcher

CodeceptJS helper for Mailcatcher

This is a helper for CodeceptJS to check for emails sent to MailCatcher during a test.


  • Download mailcatcher.js to your project that has CodeceptJS and make sure to add got as npm dependency (or replace the usages of got in this helper by your preferred http library).
  • Make sure the application you're testing is sending the emails to a mailcatcher instance.

In your codecept.config.js add something like this to your helpers configuration:

"helpers" : {
  "mailcatcher": {
    "require": "./helpers/mailcatcher.js",
    "host": process.env.MAIL_HOST || "http://localhost:1080"

In a test, you should be now able to use:

I.waitForText('Sign up');
I.fillField('email', '');'Sign up');
I.waitForText('Check your mailbox');

const email = await I.receivedAnEmail('', 'Continue your sign up.');

// do something with the email

Our application generates a unique signup confirmation link, I also made a helper-method (as page-object) to open a link from an email:

openLinkFromEmail(emailBody, linkBase) {
  const regex = new RegExp(`https?:\/\/(.*)${linkBase}(.*)`, 'm');
  const result = regex.exec(emailBody);

  if (result === null) {
	  throw new Error(`cannot find link ${linkBase}`);


which can then be used in the test as such:

const email = await I.receivedAnEmail('', 'Continue your sign up.');

I.openLinkFromEmail(email.body, '/signup/');
I.waitForText('Create your account');
const got = require('got');
class Mailbox extends Helper {
// before each suite, empty the mailbox
async _beforeSuite() {
return await got.delete(`${}/messages`);
async receivedAnEmail(to, subject) {
const messages = await this.__listMessages();
const mail = messages
.filter(m => m.subject === subject)
.filter(m => m.recipients.filter(r => r.indexOf(to) > -1))
if (mail === undefined) {
throw new Error(`Did not receive any email with subject: ${subject}`);
const response = await got.get(`${}/messages/${}.plain`);
return {...mail, body : response.body };
async __listMessages() {
// wait a bit so the email can arrive in the mailbox
await sleep(1500);
const response = await got.get(`${}/messages`, {json: true});
return response.body;
module.exports = Mailbox;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment