如何使用 Puppeteer 从当前页面重定向到另一个页面后获取 URL?

问题描述 投票:0回答:3

我是Aadarshvelu!最近开始使用 JestPuppeteer 测试我的 Web 应用程序代码。所以我有一个页面,所有凭证都已填充Puppeteer。但是当 SummitButton('signBtn') 单击 POST 过程开始

有没有处理POST请求的测试?..

或者

我如何知道测试已完全完成?

或者

测试运行时如何获取重定向页面URL?

这是我的代码!

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', '[email protected]');
    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);
javascript node.js jestjs backend puppeteer
3个回答
17
投票
  1. 是否有处理 POST 请求的测试?..
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. 我如何知道测试已完全完成?
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. 测试运行时如何获取重定向页面 URL?

例如,如果网站 http://example.com 有一个重定向到 https://example.com,则该链将包含一个请求:

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'

如果网站 https://google.com 没有重定向,则链将为空:

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


0
投票

await page.click('#signBtn')

在此之后只需制作另一页


const [, page2] = await browser.pages();


这是您的重定向页面网址👇

  const redirectPageUrl  = page2.url();
  console.log(redirectPageUrl);

0
投票

await page.goto(..)
之后,只需执行
page.url()
。发生任何重定向后,它将为您提供最终网址。

© www.soinside.com 2019 - 2024. All rights reserved.