Creating login and logout as a new command in Cypress to test tests that needs authentication

Cypress Aug 15, 2021

In this short article my idea is to explain how easy is to add new commands in Cypress.io framework. This necessity appear when I needed run some tests but I couldn't stay without an authentication state.

Add a new command

Within support -> commands.js is the place where we can add new features in Cypress, so we are going to create the login and logout using Firebase library.

Is very important you add the snippet below to initialize the Firebase.

import firebase from 'firebase';
const conf = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
}
firebase.initializeApp(conf);

The next step is add our new commands:

Cypress.Commands.add('login', (email, password) => {
    return firebase.auth().signInWithEmailAndPassword(email, password);
})

Cypress.Commands.add('logout', () => {
    return firebase.auth().signOut();
})

Congratulations 🥳, you have two new commands ready to use!

Using your command

describe("Your test", function() {
    beforeEach(function() {
        cy.login("email@gmail.com", "1234")
    }
}

What will happens now? Each time you call any it("") test, you will execute the login before the test runs.