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

Aad*_*elu 3 javascript backend node.js jestjs puppeteer

我是阿达什维卢!最近开始使用JestPuppeteer测试我的 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);
Run Code Online (Sandbox Code Playgroud)

Edi*_*nto 8

  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
Run Code Online (Sandbox Code Playgroud)
  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
Run Code Online (Sandbox Code Playgroud)
  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'
Run Code Online (Sandbox Code Playgroud)

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

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

  • 嗨@EdiImanto,我真的很喜欢你的回答。您能告诉我如何使用 Puppteer 从代理服务器加载所有资源,如 css、js 和图像吗? (2认同)