Social Login using Cypress 12.7.0
Tags: cypress, social, login, automation
Published: 2023-03-11 08:48:08

Hi guys !!!!
I am writing this after a long time. Today i am going to share an interesting topic under cypress automation tool, which is social login. Normally we do sign in just by entering the username and password without signin using any sort of social authentication such as google, github, microsoft etc.

So, today I am here to share, how to perform social login using automation tool which is cypress. Let move step by step

Step 1
Create the cypress project, by entering following commands

```
npm init
npm install cypress --save-dev
npx cypress open
```

Step 2
Enter the below line of code under cypress.config.js/ts. This code will check whether Cypress will search for and replace obstructive code in third party .js or .html files. (This piece of code prevent you from displaying 403 error page of Google after entering credentials and to dive into microsoft login page to enter credentials)
```
experimentalModifyObstructiveThirdPartyCode: true,
```

Step 3
Now you have successfully created the cypress project. Now it's time to create social login automation script using cypress. In here, i will guide on create social login of google, github and microsft. we can perform same code for facebook sign in as well
Without further delay, Let's dive in automation script

```
describe("1.1- Sign in with Google",
    function () {
    it('1.1.1- Sign in with Google Sample Test', () => {
        
    logIntoGoogle("test98@gmail.com","test@1234")
    });
    });


function logIntoGoogle(username, password) {

    Cypress.on(
        'uncaught:exception',
        (err) =>
          !err.message.includes('ResizeObserver loop') &&
          !err.message.includes('Error in protected function')
      )
    
  cy.visit('https://www.sample.lk/')
  cy.contains("Login").click()
  
  cy.get('[class="btn--1gFez tertiary--5kHib small--1MQ15 button--juoup gtm-google-login"]').click();
  
  

  cy.origin(
    'https://accounts.google.com',
    {
      args: {
        username,
        password,
      },
    },
    ({ username, password }) => {
      Cypress.on(
        'uncaught:exception',
        (err) =>
          !err.message.includes('ResizeObserver loop') &&
          !err.message.includes('Error in protected function')
      )

      cy.get('input[type="email"]').type(username, {
        log: false,
      })
      // NOTE: The element exists on the original form but is hidden and gets rerendered, which leads to intermittent detached DOM issues
      cy.get('[class="VfPpkd-LgbsSe VfPpkd-LgbsSe-OWXEXe-k8QpJ VfPpkd-LgbsSe-OWXEXe-dgl2Hf nCP5yc AjY5Oe DuMIQc LQeN7 qIypjc TrZEUc lw1w4b"]').click().wait(4000)
      cy.get('[type="password"]').type(password, {
        log: false,
      })
      cy.get('[class="VfPpkd-LgbsSe VfPpkd-LgbsSe-OWXEXe-k8QpJ VfPpkd-LgbsSe-OWXEXe-dgl2Hf nCP5yc AjY5Oe DuMIQc LQeN7 qIypjc TrZEUc lw1w4b"]').click().wait(4000)
      
    }
  )

  cy.get('.login-icon-container--3oQMU > .justify-content-flex-start--1Xozy > .header-link--woAbP').click();
  cy.contains("Test Sample")
}
```
Now let me give the brief idea on this code structure. In here we are performing google sign in for a sample application. Initially it visits the application and clicks the login button. As next step, it will dive into login page. We can observe multiple social login options are available for user to choose. In this case, we are choosing google sign in. Once "sign in with google" is clicked, it will direct you to another page which is "https://accounts.google.com", to enter our credentials. But we can observe, intially we are in one url, and now we are in different url, this situation we called Multi-domain testing. To handle this multi-domain testing, we wrap the new different url under command cy.origin(), which you can observe on the above code structure. Then once we entered to new url, we enter the username and password. Also since we move from one domain to another domain, we may able to get uncaught error exception failure. To handle them, we use

```
Cypress.on(
        'uncaught:exception',
        (err) =>
          !err.message.includes('ResizeObserver loop') &&
          !err.message.includes('Error in protected function')
      )
```

the above code within origin. After successful login, it will automatically redirect you to your desired website, which you mentioned under cy.visit(). Also, I have added a small piece of code after redirecting to verify whether the desired page has appeared

Step 4
Now we have done with all the steps. Time has come to check whether the above steps works fine without failure. To verify it, you just need to run the below code in your terminal

```
npx cypress open
```

Let me give the code structure for github signin and microsft signin as well

```
describe("1.1- Sign in with Google",
    function () {
    it('1.1.1- Sign in with Google Sample Test', () => {
        logIntoMicrosoft("test98@gmail.com","test@1234")


        

    });
    });


    function logIntoMicrosoft(username, password) {
        cy.visit('https://www.sample.lk/')
        cy.contains("Login").click()
        cy.get('[data-testid="login-page-sign-in-with-microsoft"]').click()
      
   
      
        cy.origin(
          'https://login.microsoftonline.com',
          {
            args: {
              username,
              password,
            },
          },
          ({ username, password }) => {
            cy.get('input[type="email"]').type(username)
            cy.get('input[type="submit"]').click()
            // cy.get('input[type="password"]').type(password, {
            //   log: false,
            // })
            // cy.get('input[type="submit"]').click()
            // cy.get('#idBtn_Back').click()
          }
        )

        

        cy.origin(
            'https://login.live.com',
            {
              args: {
                username,
                password,
              },
            },
            ({ username, password }) => {
              //cy.get('input[type="email"]').type(username)
              //cy.get('input[type="submit"]').click()
              cy.get('input[type="password"]').type(password, {
                log: false,
              })
              cy.get('input[type="submit"]').click()
              cy.get('#idBtn_Back').click()
            }
          )
        
      }
```
The above code structure for microsoft signin. Here, we need to go to 2 origin, one to enter username and another origin to enter password.

Finally, let's go to github signin

```
describe("1.1- Sign in with Github",
    function () {
    it('1.1.1- Sign in with Github Sample Test', () => {
        
        cy.visit('https://www.sample.lk/')
        cy.contains("Login").click()
        cy.get('[data-testid="login-page-sign-in-with-github"]').click()


        cy.origin('https://github.com', () => {

        Cypress.on('uncaught:exception', (err, runnable) => {
            // returning false here prevents Cypress from
            // failing the test
            return false
        })

            cy.get('[id="login_field"]').type("test98@gmail.com")
            cy.get('[id="password"]').type("test@1234");
            cy.get('[class="btn btn-primary btn-block js-sign-in-button"]').click();

            Cypress.on('uncaught:exception', (err, runnable) => {
                // returning false here prevents Cypress from
                // failing the test
                return false
            })
            

        })

        cy.wait(10000)


        

    });
    });
```

I hope this article will be really helpful for you all if you planning to social authentication using cypress automation for your testing.
If you have any questions, feel free to drop your comment, so then i can able to help you

Thank you