我正在使用chrome puppeteer库直接运行浏览器集成测试.我现在在单个文件中编写了一些测试.有没有办法并行运行它们?实现这一目标的最佳方法是什么?
要并行运行 puppeteer 实例,您可以查看我写的这个库:puppeteer-cluster
它有助于在多个浏览器、上下文或页面中并行运行不同的 puppeteer 任务,并处理错误和浏览器崩溃。这是一个最小的例子:
const { Cluster } = require('puppeteer-cluster');
(async () => {
const cluster = await Cluster.launch({
concurrency: Cluster.CONCURRENCY_CONTEXT, // use one browser per worker
maxConcurrency: 4, // cluster with four workers
});
// Define a task to be executed for your data
cluster.task(async ({ page, data: url }) => {
await page.goto(url);
const screen = await page.screenshot();
// ...
});
// Queue URLs
cluster.queue('http://www.google.com/');
cluster.queue('http://www.wikipedia.org/');
// ...
// Wait for cluster to idle and close it
await cluster.idle();
await cluster.close();
})();
Run Code Online (Sandbox Code Playgroud)
您还可以像这样直接将函数排队:
const cluster = await Cluster.launch(...);
cluster.queue(async ({ page }) => {
await page.goto('http://www.wikipedia.org');
await page.screenshot({path: 'wikipedia.png'});
});
cluster.queue(async ({ page }) => {
await page.goto('https://www.google.com/');
const pageTitle = await page.evaluate(() => document.title);
// ...
});
cluster.queue(async ({ page }) => {
await page.goto('https://www.example.com/');
// ...
});
Run Code Online (Sandbox Code Playgroud)
// My tests contain about 30 pages I want to test in parallel
const aBunchOfUrls = [
{
desc: 'Name of test #1',
url: SOME_URL,
},
{
desc: 'Name of test #2',
url: ANOTHER_URL,
},
// ... snip ...
];
const browserPromise = puppeteer.launch();
// These test pass! And rather quickly. Slowest link is the backend server.
// They're running concurrently, generating a new page within the same browser instance
describe('Generate about 20 parallel page tests', () => {
aBunchOfUrls.forEach((testObj, idx) => {
it.concurrent(testObj.desc, async () => {
const browser = await browserPromise;
const page = await browser.newPage();
await page.goto(testObj.url, { waitUntil: 'networkidle' });
await page.waitForSelector('#content');
// assert things..
});
});
});
Run Code Online (Sandbox Code Playgroud)
来自https://github.com/GoogleChrome/puppeteer/issues/474
编写https://github.com/quicksnap
| 归档时间: |
|
| 查看次数: |
4096 次 |
| 最近记录: |