当前位置: 首页 > news >正文

playwright 实现自动上传,多元素操作

1. 文件上传

Playwright中,使用locator.setInputFiles()完成文件上传操作。

单个文件

await page.getByLabel('Upload file')
  .setInputFiles(path.join(__dirname, 'myfile.pdf'));

多个文件

await page.getByLabel('Upload files')
  .setInputFiles([
    path.join(__dirname, 'file1.txt'),
    path.join(__dirname, 'file2.txt'),
]);

清除文件

传入空数组即可

await page.getByLabel('Upload file')
  .setInputFiles([]);

内存缓存

// Upload buffer from memory
await page.getByLabel('Upload file').setInputFiles({
  name: 'file.txt',
  mimeType: 'text/plain',
  buffer: Buffer.from('this is test')
});

2. 事件监听page.on('filechooser')

文件上传通常实现类似于

<input type="file">..

如果不是类似上面的动态创建方式的话,就需要监听对应event

// Start waiting for file chooser before clicking. Note no await.
const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByLabel('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));

3. 完整示例

3.1 Playwright项目配置

NodeJS为例,配置如下 确保你的项目已经配置好Playwright。如果还没有,可以使用以下命令安装Playwright

npm install playwright

3.2 编写上传自动化测试

import { test, expect }from'@playwright/test';
import*as path from'path';

// 文件路径
const filePath = path.resolve(__dirname,'tests/fixtures/demo.zip');

// 具体的测试用例
test('文件上传自动化测试', async ({ page })=>{
// 打开目标页面
  await page.goto('https://commitquality.com/practice-file-upload');

// 找到文件输入元素
const inputFile = await page.locator('input[type="file"]');

// 上传文件
  await inputFile.setInputFiles(filePath);

// 验证文件是否上传成功
  await expect(page.locator('text=demo.zip')).toBeVisible();
});

小结论

文件自动化上传在Playwright中是比较容易容易的,主要是调用.setInputFiles()方式实现,从而轻松实现自动化文件上传的交互操作。

多元素操作

在自动化测试中,操作和验证多个元素是常见的需求。Playwright 提供了丰富的API方法来操作和验证页面上的多个元素,包括 .all().count().first().last().nth().toHaveCount() 等

4. 介绍

Playwright是一个功能强大的自动化测试库,支持跨浏览器测试。它不仅可以操作单个元素,还提供了多种方法来操作和验证多个元素。这些方法使测试代码更加简洁和易读,同时提高了测试的可维护性。

5. 相关方法详解

5.1 .locator()API

.locator()支持如下定位策略,返回匹配成功的元素,可能包含多个:

css

const button = page.locator('button.submit');

xPath

const listItem = page.locator('//ul/li[3]');

ID

const passwordField = page.locator('#password');

text

const heading = page.locator('text="Welcome!"');

组合

const loginButton = page.locator('text="Login" >> css=button');

5.2 .getBy()系列

.getByText()

page.getByText('world');

.getByAltText()

await page.getByAltText('Playwright logo').click();

.getByRole()

await page.getByRole('checkbox', { name: 'Subscribe' }).check();

.getByLable()

await page.getByLabel('Username').fill('john');

.getByPlaceHolder()

await page
    .getByPlaceholder('name@example.com')
    .fill('playwright@microsoft.com');

.getByTitle()

await expect(page.getByTitle('Issues count')).toHaveText('25 issues');

.getByTestId()

await page.getByTestId('directions').click();

5.3 .and().or()组合

.and()

// .and组合
const button = page.getByRole('button').and(page.getByTitle('Subscribe'));
expect(button).toHaveCount(1); // 断言数量

.or()

//.or组合
const newEmail = page.getByRole('button', { name: 'New' });
const dialog = page.getByText('Confirm');
await expect(newEmail.or(dialog)).toBeVisible();

5.4 多元素选择

以下一组api,针对定位结果中的多元素进行操作,包括个数计算、选择某元素,断言个数等。

.all()

.all() 方法返回一个包含所有匹配元素的数组。

for (const li of await page.getByRole('listitem').all())
  await li.click();

.count()

.count() 方法返回匹配元素的数量。

const count = await page.locator('selector').count();
constole.log(count);

.first()

.first() 方法返回第一个匹配元素。对于文本类定位,一般文本类型,加上这个会更不易出错。

await page.locator('搜索').first().click;

.last()

.last() 方法返回最后一个匹配元素。

await page.locator('搜索').last().click;

.nth()

.nth(index)方法返回指定索引的匹配元素(索引从 0 开始)。

const banana = await page.getByRole('listitem').nth(2);

.toHaveCount()

.toHaveCount(count)方法用于断言匹配元素的数量。

const list = page.locator('list > .component');
await expect(list).toHaveCount(3);

5.5 多元素操作

.click():点击

await locator('#id').click();

.fill():填充内容

await locator('#box').fill('text');

.textCount():获取文本

const text = await locator('#id').textContent();

.toBeVisible(): 可见性

await expect(locator).toBeVisible();

6. 实战示例

以下是一个综合示例,展示了如何在实际测试中使用这些方法:

import { test, expect }from'@playwright/test';

test('comprehensive example', async ({ page })=>{
  await page.goto('https://example.com');

// 获取所有匹配元素
const allElements = await page.locator('selector').all();
  console.log(`Total elements: ${allElements.length}`);

// 获取元素数量
const count = await page.locator('selector').count();
  console.log(`Element count: ${count}`);

// 操作第一个元素
  await page.locator('selector').first().click();

// 操作最后一个元素
  await page.locator('selector').last().click();

// 操作第三个元素(索引从 0 开始)
  await page.locator('selector').nth(2).click();

// 断言元素数量
  await expect(page.locator('selector')).toHaveCount(3);
});

结论

在自动化测试中,操作和验证多个元素是不可避免的任务。Playwright 提供的 .all().count().first().last().nth().toHaveCount() 等方法,使得这些操作更加简洁和高效,让你在自动化测试项目中,提高测试的稳定性和可维护性。

相关文章:

  • 性能:React 实战优化技巧 之 函数闭包
  • 一文讲解Redis为什么读写性能高以及I/O复用相关知识点
  • python读取pdf文档
  • 学习 `@PreDestroy`:Java EE/Jakarta EE 生命周期回调
  • web安全:跨站请求伪造 (CSRF)
  • Spark(2)linux和简单命令
  • Python 关于顶层对象
  • k8s Container runtime network not ready
  • 知识图谱-学习计划
  • 基于eBPF的全栈可观测性系统:重新定义云原生环境诊断范式
  • YOLOv12改进 | 注意力篇 | YOLOv12引入CBAM注意力机制
  • 今日行情明日机会——20250220
  • 调用click.getchar()时Windows PyCharm无法模拟键盘输入
  • 【狂热算法篇】探秘图论之Dijkstra 算法:穿越图的迷宫的最短路径力量(通俗易懂版)
  • mysql查看binlog日志
  • 【Python修仙编程】(一) Python3灵基初筑(2)
  • Upwork提案模板:如何写出吸引客户的提案
  • 记录几个U9的逻辑
  • 将RocketMQ集成到了Spring Boot项目中,实现站内信功能
  • python-leetcode 40.二叉树的层序遍历
  • 专家解读上海一季度经济数据:经济韧性在增强,民企活力不可小觑
  • 蔚来李斌:当下国际贸易环境有不确定性,但坚信中国汽车产业最终将占全球四成份额
  • A股三大股指涨跌互现:人形机器人产业链爆发,两市成交超1.2万亿元
  • 张又侠董军分别与印尼国防部长会见会谈
  • 王忠诚出任四川遂宁代市长,此前为成都市政府秘书长
  • 如何保护人工智能领域的知识产权?上海市知识产权局局长解答