User Authentication in automation with Cypress and Playwright

Kishor Munot
5 min readDec 13, 2024

--

Handle User Authentication

Hello Readers,

I’m going on a short vacation next week so before I go on a short vacation I thought we’d discuss one of the new topics we’ve been working on and then I’ll go on my vacation setting an automatic publishing date for that blog for a weekend and then when I get back from my short vacation your thoughts will give me some extra strength to write more interesting topics. So let’s start..

| Must Read | API Authentication and Authorization with Cypress | Medium

Start with story…

Those who have had experience working with Cypress.io and Playwright know that they are truly a wonderful tools that provides great opportunities for developing and implementing high-quality and reliable tests in your projects. Therefore, all that remains for us is to be able to make the best use of these opportunities. They always fight to bring new and best things to the community and thus provide a beautiful journey experience while doing web automation.

The fact is that over the past few years, I have encountered various approaches to writing tests, sometimes with fundamentally different models and templates for building test scenarios and test cases. And it often happened that already written tests needed serious improvement or even complete restructuring, mainly to ensure their reliability and reduce the time it takes to run them. It’s obvious that as a QA engineer, it is crucial to continuously evaluate and optimize testing processes to ensure the highest possible level of quality assurance.

This is the reason for writing or publishing the new story. I want to do authentication by e-mail and mobile sms for every new login as well as for user who forgot password as well as for user who is signing up. I was looking for ways to use or can be used in Cypress as well as Playwright because both tools make good use of javascript and if we find a way to reach the desired destination we can still get there.

How to handle user authentication in Cypress

We use multiple type of authentication and we need to authticate and give access to the user so we can handle this with plugin called “mailosaur”.

Mailosaur a service that creates an email inbox for you. What’s special about it is, that you can access it not only via their interface, but also via their API. All of email content and metadata can be viewed in plain text, HTML, or parsed to JSON, where you can view all links, attachments or images.

My favorite part is the ability to wait for a specific message to arrive. This means you can access all of that information within few milliseconds and then use them further in your test.

First, we need to follow their documentation so that you don’t encounter any blocks during user authentication.

Install the command below in your Cypress framework root level and then check your package.json file for an entry about the plugin under dependencies.[Close and reopen the editor if the entry is not visible]

npm install cypress-mailosaur
{
"dependencies": {
"cypress": "4.4.1",
"mailslurp-client": "8.7.8"
}
}

Then, Import Mailosaur into your Cypress project

import "cypress-mailosaur";

Then, Configure your API key in your project. In order to connect to Mailosaur, you need to add an API key to your tests. You access your API key via in the account settings area.

Add your Mailosaur API key to cypress.config.js, in your project folder

module.exports = defineConfig({
env: {
MAILOSAUR_API_KEY: "your-key-here",
},

// ...
});

Now, lets talk about use of above configration in our tests.

Add your Mailosaur API key to cypress.config.js, in your project folder

module.exports = defineConfig({
env: {
MAILOSAUR_API_KEY: "your-key-here",
},
cy.visit("https://producturl.com/",{timeout: 80000});
cy.get('.signIn').click();
cy.get('#username').type(username); // Mailosur inbox email
cy.get('#password').type(password);
cy.get(#loginButton).click();
cy.get('#SendEmail').should('be.visible');
cy.get('#SendSMS').should('be.visible');
cy.get('#SendEmail').click();

I am trying to automate login process with cypress inbuilt methods in above test. I have not used any pom pattern for clear understanding. After clicking on SendEmail you will get an email along with an otp or login success link in your account.

After you sign up on Mailosaur web application you will get Mailosaur email address, server id along with inbox account. First create an account on Mailosaur and use that in your project. Then use the email address generated on Mailosaur for the sign up process in your project and then log in with that account in your web product application.

Now, in the above mentioned snippet code, we are generating an email with accessCode or accessUrl.

Next step is to check our Mailosaur inbox for the Password or accessUrl email based on its subject (after a 10 seconds wait in order for the email to get delivered in our inbox).

cy.wait(10000);
cy.mailosaurListMessages("ihl97444") // ServerID
.then((result) => {
const email = result.items[0];
expect(email.subject).to.equal("IRCTC Email geneation");
return cy.mailosaurGetMessageById(email.id);
})

We can fetch the OTP from email by their API response.

cy.mailosaurGetMessage("ykzlsgdl", {sentTo: emailAddress,}).then((email) => {
cy.log(email.subject);
const accessCode = email.html.codes[0].value;
cy.log(Number(accessCode));
cy.log("accessCode " + accessCode);
});

//Will pass this accessCode in type method and click on Submit.
loginPage.AccessCode().type(accessCode);
homePage.Submit().click();

How to handle user authentication in Playwright

Now, we can handle authentication in playwright with same API of mailsour with playwright code. so let’s start..

After configuring playwright in your system just install the mailsour in your system.

npm install mailosaur;

Import Mailosaur into your project

In order to connect to Mailosaur, you need an API key. You access your API key via in the account settings area.

In your tests, simply import the Mailosaur library, using your API key, at the top of your spec file.

import { test, expect } from "@playwright/test";
import MailosaurClient from "mailosaur";

const mailosaur = new MailosaurClient("YOUR_API_KEY_HERE");

After above configration you can user mailosaur API in your projects.

test("password reset", async ({ page }) => {
const serverId = "YOUR_SERVER_ID_HERE";
const testEmailAddress = `some-test-run123@${serverId}.mailosaur.net`;

// Navigate to a password reset page, and submit the form to trigger an email
await page.goto("https://example.mailosaur.com/password-reset");
await page.fill("#email", testEmailAddress);
await page.click('button[type="submit"]');

// Connect to Mailosaur, and wait for that email to arrive
const email = await mailosaur.messages.get(serverId, {
sentTo: testEmailAddress,
});

expect(email.subject).toBe("Password reset");
});

After obtaining the link or OTP, you can continue with your test journey. Opening link, setting up new password, and then finally logging in to application. This resembles real life behavior more closely, connecting and integrating each step.

Have you tried any of these scenarios? Share your experiences with us!

What are your thoughts on this topic? I’d like to hear your opinions, feedbacks in the comments below!!

Keep reading and keep testing.

Thank you..

--

--

Kishor Munot
Kishor Munot

Written by Kishor Munot

QA Test Lead | Writer | Adventure | Nature

No responses yet