Skip to content
Advertisement

How To Get The URL After Redirecting from Current Page To Another Using Puppeteer?

I’m Aadarshvelu! Recently Started Testing My WebApp Code Using Jest With Puppeteer. So I Have Page Which All Credentials Have Been Filled With Puppeteer.But When SummitButton(‘signBtn’) Clicked POST process Starts

Is There Any Test That Process POST Request?..

Or

How Do I Know Test Has Been Completely Finished?

Or

How to Get The Redirect Page URL While Test Running?

This Is My Code!

const puppeteer = require('puppeteer');
const timeOut = 100 * 1000;

test("Full E2E Test!" , async () => {

    const browser = await puppeteer.launch({
        headless: false,
        slowMo:30,
        args: ['--window-size=1920,1080']
    });

    const page = await browser.newPage();

    await page.goto('https://mypass-webapp.herokuapp.com/signUp');

    await page.click('input#email');
    await page.type('input#email', 'Automation@puppeteer.com');
    await page.click('input#username');
    await page.type('input#username' , "puppeteer");
    await page.click('input#password');
    await page.type('input#password' , "puppeteer");
    await page.click('#signBtn').then(await console.log(page.url()));

    // Here I Need a Test That Checks The Current Page!

    await browser.close();

} , timeOut);

Advertisement

Answer

  1. Is There Any Test That Process POST Request?..
const [response] = await Promise.all([
  page.click('input[type="submit"]'), // After clicking the submit
  page.waitForNavigation() // This will set the promise to wait for navigation events
// Then the page will be send POST and navigate to target page
]);
// The promise resolved

  1. How Do I Know Test Has Been Completely Finished?
const [response] = await Promise.all([
  page.click('a.my-link'), // Clicking the link will indirectly cause a navigation
  page.waitForNavigation('networkidle2') // The promise resolves after navigation has finished after no more than 2 request left
]);
// The promise resolved

  1. How to Get The Redirect Page URL While Test Running?

For example, if the website http://example.com has a single redirect to https://example.com, then the chain will contain one request:

const response = await page.goto('http://example.com');
const chain = response.request().redirectChain();
console.log(chain.length); // Return 1
console.log(chain[0].url()); // Return string 'http://example.com'

If the website https://google.com has no redirects, then the chain will be empty:

const response = await page.goto('https://google.com');
const chain = response.request().redirectChain();
console.log(chain.length); // Return 0

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement