Skip to content

[Feature] Ability to customize the screenshot description on the image #23326

@cenfun

Description

@cenfun

Context

Usually we need to share the screenshots with the team or someone. When opening the screenshot, it would be great if there is a related description on the screenshot, for example showing the test title and time.

What we tried

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

test('my test', async ({ page }, testInfo) => {

    await page.goto('https://playwright.dev/');

    const description = `Description for ${testInfo.title} (${new Date().toLocaleString()})`;

    // before screenshot, draw something in the page
    await page.evaluate(function(msg) {
        const elem = document.createElement('div');
        elem.className = 'screenshot-helper';
        elem.style.cssText = `pointer-events: none;
            position: absolute; z-index: 99999; 
            left: 20px; bottom: 20px; 
            font-size: 20px; font-weight: bold; padding: 5px 20px;
            opacity: 0.68; color: #ff0000; border: 1px solid red;`;
        elem.innerHTML = msg;
        document.body.appendChild(elem);
    }, description);

    // take screenshot
    await page.screenshot({
        path: testInfo.outputPath('my-screenshot.png')
    });

    // after screenshot, remove the helper message
    await page.evaluate(function(msg) {
        const elem = document.querySelector('.screenshot-helper');
        if (elem) {
            elem.remove();
        }
    });

});

test-failed-1

Problem

We can only manually add the screenshot description, but not automatically add it when the test fails.

Suggested solution

Maybe we can consider adding an option to allow screenshot to support hooks, just like auto fixtures

// playwright.config.js
export default {

    use: {
        screenshot: 'only-on-failure'
    },
    screenshotFixture: async ({ page, testInfo }, use) => {
            // before screenshot
            await page.evaluate(...);

            // take screenshot
            await use();

            // after screenshot
            await page.evaluate(...);
    },
    reporter: [
        ['list']
    ]
};

or separate beforeScreenshot and afterScreenshot

// playwright.config.js
export default {

    use: {
        screenshot: 'only-on-failure'
    },
    beforeScreenshot: async ({ page, testInfo }) => {
            
    },
    afterScreenshot: async ({ page, testInfo }) => {
            
    },
    reporter: [
        ['list']
    ]
};

Thanks,

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions