How do you do that

How does one take a screenshot in Playwright if a Jest test fails? This was sort of the question brought up by a team lead at work. I wondered why that would be needed, but I quickly answered my own question. Playwright follows async/await fairly closely, and if an await fails, then Jest won’t exaclty help with identifying where the error is. From what I’ve seen, all Jest will mostly print a timeout error. So a screenshot could probably help to know where a thrown error came from.

So I searched for an answer, and I eventually found one! Here is the huge code bit in my jest.setup.js file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
global.it = async (name, func) => {
  return await test(name, async () => {
    try {
      await func();
    } catch (e) {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getUTCMonth() + 1;
      const dateOfMonth = date.getUTCDate();
      const hour = date.getUTCHours();
      const minute = date.getUTCMinutes();
      const sec = date.getUTCSeconds();
      const dateString = `${year}-${month}-${dateOfMonth}-${hour}-${minute}-${sec}`;

      const errorScreenshotPath = `screenshots/${browserName}-${dateString}-${name.replace(
        / /g,
        "_"
      )}.png`;

      const captureScreenshots = process.env.CAPTURE_SCREENSHOTS === "true";

      if (captureScreenshots) {
        await mkdirp("screenshots");

        await page.screenshot({
          path: errorScreenshotPath,
        });
      }

      throw e;
    }
  });
};

The answer was to override the Jest it function with something that took screenshots on fail. Surround the testing function with a try/catch block in case any one of those await statements throws and error. If an error is thrown, catch that error and make a screenshot. With the error handling, I added in a timestamp, test name, and browser name for the screenshot file name. I also used mkdirp to see if the directory exists or not.

And so this is the way that I liked. I could take a screenshot of the Playwright automation test on fail. A lot of the other potential solutions looked like they could work, but exploring the other solutions didn’t prove anything. This previous solution that I have shown was simple! And because of its simplicity, I think I will stick to this if I ever need a way to capture a screenshot on a test failure.