Search code examples
google-oauthpuppeteere2e-testing

E2e testing for Google Login with Puppeteer


I'm new to Puppeteer and trying to write an e2e test for a React app that enables logins using the GoogleLogin component from @react-oauth/google.

The code below works until the Google sign in window opens, but then I don't know how to access elements. I've looked at the element and I know that there's an input of type email, so I'd like to wait for that selector, but page doesn't seem to be the place to access it.

How do I move to the next step with this test?

const chalk = require( 'chalk' );

class LoginAccount {
  constructor( page ) {
    this.url = "http://localhost:3000"
    this.page = page;
  }

  async login( username, password ) {
    try {
      const navigationPromise = page.waitForNavigation();
      await this.page.goto( this.url );
      const selector = '[role="button"]';
      await this.page.waitForSelector( selector );
      const button_handler = await page.$(selector);
      await button_handler.evaluate(b => b.click());
      await navigationPromise

      const email_field = 'input[type="email"]'
      await page.waitForSelector( email_field )

      // Times out here

      console.log("Got email input")
      await this.page.type( email_field, username );

    } catch ( err ) {
      console.log( chalk.red( 'ERROR => ', err ) );
    }
  }
}

module.exports = ( page ) => new LoginAccount( page );

Solution

  • I was able to solve this. The browser.waitForTarget method gets me a handle to the new browser window that I need. The modified code below (starting just before the button click) works correctly:

      const pageTarget = page.target();
    
      await button_handler.evaluate(b => b.click());
    
      const newTarget = await browser.waitForTarget(target => target.opener() === pageTarget);
      const newPage = await newTarget.page();
    
      const email_field = 'input[type="email"]'
      await newPage.waitForSelector( email_field )
    
      console.log("Got email input")