Skip to content

Instantly share code, notes, and snippets.

@schmkr schmkr/README.md
Created Aug 3, 2018

Embed
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.

usage

  • 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.amOnPage('/signup');
I.waitForText('Sign up');
I.fillField('email', 'me@example.com');
I.click('Sign up');
I.waitForText('Check your mailbox');

const email = await I.receivedAnEmail('me@example.com', '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}`);
  }

	this.amOnPage(`${linkBase}${result[2]}`);
}

which can then be used in the test as such:

const email = await I.receivedAnEmail('me@example.com', '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(`${this.config.host}/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))
.shift();
if (mail === undefined) {
throw new Error(`Did not receive any email with subject: ${subject}`);
}
const response = await got.get(`${this.config.host}/messages/${mail.id}.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(`${this.config.host}/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
You can’t perform that action at this time.