playwrightplaywright-typescript

playwright (typescript) custom default snapshot name including value set in config use settings


In the PlaywrightTestConfig we set a custom value in the use section i.e

export default defineConfig {   
  use: {
    myKey: 'myvalue'
  }
}

This value may get overridden in the tests and I want to make the snapshots name include the value from myKey without the person writing the test having to add the snapshot name i.e get picked up by default as if it was set in the snapshotPathTemplate within the project config. So a test file called example.test.ts with test called my test that does expect(page).toHaveScreenshot() would generate a snapshot filename something like {testFileName}/{testFileDir}-{myKey}-{projectName}-{platform}.png (example.test.ts-snapshots/my-test-myvalue-chromium-darwin.png)

Note: I dont want to have a separate project for each combination as that would end up being a lot of combinations


Solution

  • Playwright's snapshotPathTemplate should probably get you most of the way there. The tl;dr is that Playwright provides a set of tokens you can you to generate your snapshot path automatically, and you can additionally provide your key to the string template.

    ...
      snapshotPathTemplate: `{testFileName}/{testFileDir}-${process.env['myKey']}-{projectName}-{platform}.png`,
    ...
    

    I opted to use process.env to get my custom key, but whatever way you see fit to insert your key into the snapshotPathTemplate should suffice.

    Running the above with a test output a file at something like: .../myFileName.spec.ts/mySpecFolderName-myKeyValue-chromium-darwin.png