前言
在Playwright报告中增加截图,可以很方便的帮助我们排查问题,那该怎么实现这个功能呢?本篇文章,笔者带大家一起来实现。
功能
想象一下,你现在要实现以下功能:自动导航到百度首页,截图并存储到本地,然后点击某个按钮到新的页面,再截图保存到本地,代码你可能会这么写:
test('home page screenshot', async ({ page }, testInfo) => {
await page.goto('https://www.baidu.com/');
const homeScreenshot = await page.screenshot({path: "screenshots/home.png"});
await todoPage.locator('.hotsearch-item').first().click();
const customerScreenshot = await page.screenshot({path: "screenshots/hotsearch.png"});
});
在上面的代码中,当你运行 npx playwright test
时,测试会通过,而且你还可以在本地文件夹中找到存储的截图,但是,如果你检查生成的HTML报告,你会发现,报告中并没有截图,
我们当然可以使用 npx playwright test --trace
来获取测试流程中所有图片,但是,如果我们只想获取某个瞬间的一个截图,或者保留其中一些截图,该怎么做呢?
使用 testInfo 对象
我们回到我们刚开始写的代码,会发现有个 testInfo 对象:
其实,testInfo可以帮我们实现只保留自定义的截图,具体该怎么做呢?可以看看代码:
test('home page screenshot', async ({ page }, testInfo) => {
await page.goto('https://www.baidu.com/');
const homeScreenshot = await page.screenshot();
testInfo.attach('Home Page', {
body: homeScreenshot,
contentType: 'image/png',
});
await todoPage.locator('.hotsearch-item').first().click();
const customersScreenshot = await page.screenshot();
testInfo.attach('hotsearch Page', {
body: hotsearchScreenshot,
contentType: 'image/png',
});
});
在这段代码中,我们调用了 testInfo.attach
方法,该方法可以自动将截图内容附加到你的测试报告中。
运行结果
接下来,你可以再次运行 npx playwright test
,在生成的HTML报告中,你将会看到上面代码中的截图了。
不止截图
除了截图,我们还可以添加一些其他类型,比如下面代码可以附加一个 json 文件到HTML报告中
const allCountries = await response.json();
testInfo.attach('Sample JSON', {
body: Buffer.from(JSON.stringify(allCountries)),
contentType: 'application/json',
});
在你运行完报告后,你会发现该JSON文件已经附加到测试报告中了。