Rayrun

What are the methods to maintain session data across multiple tests in Playwright?

Answer

Persisting Sessions Across Tests in Playwright

To persist sessions across multiple tests in Playwright, you can use session storage or global setup.

Session Storage

Session storage is domain-specific and doesn't persist across page loads. Playwright doesn't provide an API for this, but you can use the following snippet to save and load session storage:

// Get session storage and store it as an environment variable
let storage = await page.evaluate(() => JSON.stringify(window.sessionStorage));
fs.writeFileSync('sessionStorage.json', storage);

// Load session storage in a new context
let data = fs.readFileSync('sessionStorage.json', 'utf8');
let json = JSON.parse(data);
page.addInitScript((storage) => {
  Object.keys(storage).forEach((key) => {
    window.sessionStorage.setItem(key, storage[key]);
  });
}, json);

Global Setup

Another way to persist sessions is by using global setup. This allows you to log in once and skip the login step for all your tests. You can add a before hook that runs before each test and signs in each page with your desired credentials.

beforeEach(async ({ page }) => {
  await page.goto('https://ray.run/login');
  await page.fill('input[name="username"]', 'myUsername');
  await page.fill('input[name="password"]', 'myPassword');
  await page.click('button[type="submit"]');
});

Remember, each test should be isolated with its own local storage, session storage, and data cookies. This improves reproducibility, makes debugging easier, and prevents cascading test failures. However, some duplication is okay if it keeps your tests clearer and easier to read and maintain.

References

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

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