TestCafe end-to-end MFA testing for user sign-up and email verification

End-to-end testing with MailSlurp, NodeJS, and TestCafe.

test cafe

TestCafe is a great NodeJS framework for end-to-end testing with built in browser support. You can use MailSlurp with TestCafe to test user sign-up multi-factor authentication with real email accounts. In this post we will show you how with examples. For full code see GitHub.

MFA user sign up flow

MFA is multifactor authentication. This is a common security layer to many web applications. Commonly this involves sending a verification code to a user's email address when they sign up in order to verify their account. For this example we can use a simple React App hosted at playground.mailslurp.com. This app has a common user sign up flow that allows a user to sign up with their email address and password. Upon sign up a user is sent a confirmation code by email that they must enter into the app to confirm their account.

This is what the email looks like:

confirm

It contains a numeric code that we will use MailSlurp and a regex pattern to extract.

Automated testing

TestCafe allows you to easily write end-to-end browser tests to test an application functionality. Using MailSlurp we can test application functionality using real email accounts. TestCafe will run a browser an click elements and inputs like a normal user.

sign-up

Setting up a project

Let's get started and set up a new project. Create an empty directory and add a package json.

mkdir testproject && cd $_ && echo "{}" > package.json

Next we should install MailSlurp and TestCafe:

npm install --save testcafe mailslurp

The package.json file should look like this:

{
  "name": "javascript-testcafe",
  "description": "Email test MFA user sign up using TestCafe and MailSlurp",
  "scripts": {
    "test": "testcafe firefox mfa-test.js"
  },
  "dependencies": {
    "mailslurp-client": "^11.3.1",
    "testcafe": "^1.13.0"
  }
}

Now we are ready to write some tests.

Writing tests for TestCafe

Create a test file of any name - we will call ours test mfa-test.js.

Setup MailSlurp and fixture

TestCafe expects us to define a fixture using tagged template strings. Let's do that and add a before method to instantiate MailSlurp.

import { Selector } from "testcafe";
import { MailSlurp } from "mailslurp-client";

let mailslurp;
const password = "test-password";

// define our test that will load the playground demo app
fixture`mfa sign-up test`.page`https://playground.mailslurp.com`.before(
  async (_) => {
    // assert that we have set an api key environment variable
    const apiKey = process.env.API_KEY;
    if (!apiKey) {
      throw "No MailSlurp API KEY defined";
    }
    mailslurp = new MailSlurp({ apiKey });
  }
);

MailSlurp lets you create real test email accounts on demand and send and receive emails in tests and code. MailSlurp is free for personal use but you need an API Key. Create a free account to get your API Key. When running the tests set API_KEY=your-api-key as an environment variable to pass the API KEY to our test instance.

Testing user sign up

Now we can test the user sign up flow. To recap we need to perform the following steps:

  • Load the playground application
  • Create a test email address
  • Sign up using the email address and a test password
  • Receive a confirmation code to the email address
  • Extract the code and submit it to the app
  • Login with our verified account

The code for this is quite simple with TestCafe:

test("Can sign-up and verify account", async (t) => {
  // create email address for a test user
  const inbox = await mailslurp.inboxController.createInbox();
  // load the page and click sign up
  await t
    .expect(Selector("title").innerText)
    .eql("React App")
    .click(Selector("[data-test=sign-in-create-account-link]"));
  // wait for sign up form then fill with email address and sign up
  const emailInput = await Selector('[name="email"]')();
  await t
    .typeText(emailInput, inbox.emailAddress)
    .typeText(Selector('[name="password"]'), password)
    .click(Selector("[data-test=sign-up-create-account-button]"));
  // wait for verification code to arrive to email then extract code
  const email = await mailslurp.waitController.waitForLatestEmail(
    undefined,
    undefined,
    inbox.id,
    undefined,
    undefined,
    30000,
    true
  );
  // use regex to extract the confirmation code which is 6 digits
  const code = /([0-9]{6})$/.exec(email.body)[1];
  // now enter code to confirm
  await t
    .typeText(Selector('[name="code"]'), code)
    .click(Selector('[data-test="confirm-sign-up-confirm-button"]'));
  // now sign up
  const username = await Selector('[name="username"]')();
  await t
    .typeText(username, inbox.emailAddress)
    .typeText(Selector('[name="password"]'), password);
  const signIn = await Selector("[data-test=sign-in-sign-in-button]")();
  await t.click(signIn);
  // wait for sign up
  const h1 = await Selector("h1")();
  await t.expect(h1.innerText).eql("Welcome");
});

That's a bit of code so let's break it down:

Creating test email accounts

We can create a test email address using MailSlurp like so:

const inbox = await mailslurp.inboxController.createInbox();

Inboxes have an id and an emailAddress. We can use the emailAddress to sign up for the test app:

sign up

const emailInput = await Selector('[name="email"]')();
await t
  .typeText(emailInput, inbox.emailAddress)
  .typeText(Selector('[name="password"]'), password)
  .click(Selector("[data-test=sign-up-create-account-button]"));

Receiving emails in tests

Once signed up we need to receive the confirmation code to proceed. We can use the MailSlurp WaitForController to do so:

const email = await mailslurp.waitController.waitForLatestEmail(
  undefined,
  undefined,
  inbox.id,
  undefined,
  undefined,
  30000,
  true
);
// use regex to extract the confirmation code which is 6 digits
const code = /([0-9]{6})$/.exec(email.body)[1];

Then we can enter the code to confirm a user account. This is a common need for many user sign up flows:

sign up

Conclusion

Signing up with a confirmed user in our test app will show a happy dog:

dog

TestCafe is an excellent choice for end-to-end testing. Use MailSlurp to add real email accounts to your end-to-end test suites. Create a free account today or see the developer page for more examples.

Related content

Golang email library for sending and reading emails

Golang Email Library for sending and receiving emails in Go over SMTP or HTTP/S.

NodeJS MailSlurp SDK

Nodemailer alternatives to send and receieve email in code and tests

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

Using Email APIs to send and receive emails

Generate dynamic email addresses on demand with MailSlurp - a modern email API.

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.

How to send emails in Javascript (NodeJS)

JS SMTP email sending guide using HTML and NodeJS.

NodeMailer NPM Tutorial

Send and receive email using NodeMailer in Node JS.

How to start selenium in a background process and wait for it to start

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.

CypressJS Example

Test email sign-up. password verification and more with Cypress JS and MailSlurp.

CypressJS Email Testing

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

Java JVM Examples

Test email sending and receive emails without a mail server.

TestNG Selenium Java Example

Testing user sign up in Java using TestNG and MailSlurp test email accounts

Codeception PHP acceptance testing using real email address APIs

Write acceptance tests in PHP with real email addresses using Codeception and MailSlurp

PHP Email Test Plugins: send and receive email in PHPUnit (example code)

How to send and receive emails in PHPUnit tests.

PyTest Email Testing

Send and receive email in Pytest Python tests.

Java, Selenium

Receive emails in Java test suites using MailSlurp, Junit, and Selenium.

Receive email in PHP: using MailSlurp to send and receive emails

Test email in PHP using real email addresses

Python Robot Framework email test

Python automation email testing Robotframework plugin

Testing authentication using real email addresses in Ruby with Capybara, Cucumber, and Selenium

Cucumber example project using Capybara to test user authentication using real email addresses.

Test applications with real emails using Serenity BDD, JBehave and Selenium

Email acceptance testing with Serenity and MailSlurp. Test applications with real email addresses.

Specflow user sign-up testing with MailSlurp accounts

How to test .NET authentication and sign-up using real email accounts with MailSlurp and SpecFlow.

Jest, Puppeteer

Test email accounts in React with Jest and Puppeteer. Send and receive emails in Javascript.

.NET Selenium C#

Send and receive email in DotNET Nunit tests using Selenium and MailSlurp.

Cucumber, Ruby

Generate test email accounts with Ruby and Cucumber. Test email sign-up, password verification and more.

Webdriver, JS, WDIO

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 verification

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 authentication (2FA)

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.

How to test 2FA OTP login using SMS codes with Playwright

The ultimate guide to testing OAuth one-time-password flows with real SMS MFA. Use Playwright to automate authentication tests with programmable TXT message APIs.

Testing guide

Integration testing with disposable email accounts using CypressJS, Selenium and many other frameworks. Test OTP password login, transactional emails, notifications and more.

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

Ready to dive in?Start building email applications today.