How do I set up Playwright to select a user from a JSON file based on an environment variable?


Sure, here's how you can set up your tests to pick a user from a JSON file based on an environment variable using @playwright/test.

First, create a users.json file with the user information you want to use in your tests.

Next, in your playwright.config.ts file, import the dotenv package and read the environment variables. You can do this by calling dotenv.config(). This will read from the default .env file. If you want to specify a custom path, you can do so like this:

dotenv.config({ path: 'path/to/custom/env/file' })

Then, define an object that will hold all of your users' information. You can do this by reading from the JSON file using Node.js' built-in fs module. You can then access this object anywhere in your tests by calling process.env.USERS.

Finally, when running your tests via the command line interface (CLI), set an environment variable for which user you want to use for that particular test run. For example:

USERNAME=john npx playwright test

So, to summarize:

  1. Create a users.json file with user information.
  2. Import the dotenv package and read environment variables in playwright.config.ts.
  3. Define an object holding all users' info by reading from the JSON file.
  4. Access this object in tests via process.env.USERS.
  5. Set the environment variable for the user to use when running the CLI command.

For more tips on efficient Playwright test scripts, check out this blog post.


Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.