【问题标题】:How To Get The URL After Redirecting from Current Page To Another Using Puppeteer?使用 Puppeteer 从当前页面重定向到另一个页面后如何获取 URL?
【发布时间】:2020-02-27 22:46:47
【问题描述】:

我是 Aadarshvelu!最近开始使用 Jest 和 Puppeteer 测试我的 WebApp 代码。所以我有一个页面,其中所有凭据都被 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', '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);

【问题讨论】:

    标签: javascript node.js jestjs backend puppeteer


    【解决方案1】:
    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
    

    【讨论】:

    • 谢谢你的回答老兄!,它真的有效!!,我希望你做得很好:)
    • 嗨@EdiImanto,我真的很喜欢你的回答。你能告诉我如何使用 Puppteer 从我们的代理服务器加载所有资源,如 css、js 和图像?
    猜你喜欢
    • 2015-06-06
    • 2015-08-14
    • 2013-07-20
    • 2023-02-02
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多