In this article, we will discuss in detail how we can capture screenshots in playwright.
1. Screenshot of the current visible window
1 2 3 4 | test('Capture screenshot of the visible window', async ({page}) => { await page.goto('https://the-internet.herokuapp.com/') await page.screenshot({path: 'screenshot/visibleWindow.png'}) }) |
Upon executing this, a folder ‘screenshot’ will be created(if not already there), and the screenshot will be saved inside it.
2. Screenshot of the entire scrollable web page
1 2 3 4 | test('Capture screenshot of the entire scrollable webpage', async ({page}) => { await page.goto('https://the-internet.herokuapp.com/') await page.screenshot({path: 'screenshot/fullPage.png', fullPage: true}) }) |
Upon executing, the screenshot will be saved in the screenshot folder.
3. Screenshot of a particular element on the webpage.
1 2 3 4 5 6 | test('Capture screenshot of an element', async ({page}) => { await page.goto('https://the-internet.herokuapp.com/dropdown') await page .locator('#dropdown') .screenshot({path: 'screenshot/elementScreenshot.png'}) }) |
Here we want to take a screenshot of the dropdown field in its closed state. Upon executing, we get this:
4. Automatic Screen Capture on Test Failure.
1 2 3 4 5 6 7 8 9 10 | test('Automatically Capture screenshot when Test Fails ', async ({page}) => { await page.goto('https://the-internet.herokuapp.com/login') await expect(page.locator('#username')).toBeVisible({timeout: 2000}) await page.fill('#username', 'tomsmith1') await page.fill('#password', 'wrong-password') await page.click('button[type="submit"]') await expect(page.locator('div#flash')).toContainText( 'You logged into a secure area!' ) }) |
In the above code snippet, we intentionally gave the wrong password to make the test fail. To ensure a screenshot is captured automatically on failure, we have to do this. Go to Playwright.config.ts file and under use add the flag screenshot: ‘only-on-failure’.
Upon Executing, we could see the screenshot under the test-results folder.
Apart from the above four, the screenshot API in Playwright provides other options to capture/manipulate screenshots. You can look into them here.
Do check out 🙂