Automatically Create Playwright Traces with Jest

Share on:

In the Playwright 1.12 release, one of the new features added was the ability to create traces of test runs. I find traces to be more helpful than videos because they allow me to step through my test steps at my own pace. Unlike videos, there isn’t currently a way to configure Playwright to record traces by default. However, if you use Jest’s circus test runner, you can modify the test lifecycle using Custom Environments. To enable the circus runner, first run npm install --save-dev jest-circus, and then add the following line to your jest.config.js file:

1module.exports = {
2    // All of the rest of your config
3    testEnvironment: "./customEnvironment.js",

With the circus runner enabled, we then need a CustomEnvironment that injects Playwright traces into the test lifecycle. Create a file for the new environment (I named mine customEnvironment.js) with this content:

 1const PlaywrightEnvironment = require("jest-playwright-preset/lib/PlaywrightEnvironment")
 2    .default
 4class CustomEnvironment extends PlaywrightEnvironment {
 5    constructor(config, context) {
 6        super(config, context)
 7    }
 8    async setup() {
 9        await super.setup()
10        const { context } =;
11        await context.tracing.start({ screenshots: true, snapshots: true });
12    }
14    async teardown() {
15        await super.teardown()
16    }
18    async handleTestEvent(event) {
20        if ( === "test_done") {
21            const testPassed = event.test.errors.length === 0 ? true : false
22            const testName = /g, "_")
23            const { context } =;
24            const { browserName } = this._config
25            await context.tracing.stop({ path: `traces/${testName}-${browserName}.zip` });
26        }
27    }
30module.exports = CustomEnvironment

With this custom environment, I’m recording a trace for every test that is run. However, this could be modified to store traces on test failures, if an environment variable was set, or keep all traces by amending the trace name with the current DateTime.

Lastly, we need to amend our jest.config.js file to use our custom environment:

1module.exports = {
2    // All of the rest of your config
3    testEnvironment: "./customEnvironment.js",

And with that change, you’re done! All of your traces will be stored in the /traces directory of the project. Given that the Playwright team already allows videos to be recorded automatically, they may add a similar feature for traces. Until then, I hope this method helps!