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
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.