< Back to Blog Overview

Recording browser sessions with Playwright

2020-06-03
Recording browser sessions with Playwright

When you run headless tests with Playwright, the browser will run the test without showing any UI.


The advantage is that it is much faster to run tests this way than for example with Selenium.
One disadvantage however, is that it makes it harder to troubleshoot, because you can not record the UI into a video file.


If you're looking to record videos of your browser sessions, then you can use a NPM package called playwright-video. This package uses the DevTools protocol (more specifically Page.startScreencast) to capture screencastFrame's and stitch these together with ffmpeg.

Installation

To get started, please install the necessary packages:

npm i -D playwright-video ffmpeg-static

Run your first test

Now you're ready to run your first test with video. The example below will open a remote browser session in our cloud, and send the video frames back to you, where playwright-video will stitch these frames together into a video file.


const pw = require('playwright-core');
const { saveVideo } = require('playwright-video');

(async () => {
  const browser = await pw.chromium.connect({
    wsEndpoint: 'wss://chrome.headlesstesting.com?token=[YOUR-TOKEN]&browserVersion=dev',
  });
  const context = await browser.newContext();
  const page = await context.newPage();

  await saveVideo(page, '/tmp/video.mp4');

  await page.goto('https://headlesstesting.com/');
  await page.screenshot({ path: 'screenshot.png' });

  await browser.close();
})();

This example will open a Chrome browser in our cloud, navigate to our webpage and take a screenshot. It will save a recording of these actions in a file called /tmp/video.mp4 on your computer.


Integration with Jest or Mocha

It's also very easy to integrate this with either Jest and Mocha. Simply put the saveVideo call in your before hook to record a video of each test.


For example, with Mocha you could use this:

let capture
beforeEach(async function() {
    this.timeout(35000)
    browser = await pw.chromium.connect({
        wsEndpoint: 'wss://chrome.headlesstesting.com?token=[YOUR-TOKEN]&browserVersion=dev',
    })
    context = await browser.newContext()
    page = await context.newPage()
    capture = await saveVideo(page, `${this.currentTest.title.replace(/ +/g, '_')}.mp4`)
})
afterEach(async function() {
    await capture.stop()
})

This will use Mocha to run your tests, and for each test save the video in a MP4 file with the title of your test.

HeadlessTesting Logo

Sign up for a Free Trial

Start Headless Testing instantly.

No credit card required!