You can handle random modals in your tests by saving and loading session storage using Playwright's API. Here's how you can do it:
First, save the session storage as an environment variable in your test setup. Use page.evaluate() to execute JavaScript code on the page. Here's an example:
const sessionStorage = await page.evaluate(() => JSON.stringify(sessionStorage));
fs.writeFileSync('playwright/.auth/session.json', JSON.stringify(sessionStorage), 'utf-8');
This code gets the session storage from the current page and saves it as a JSON file named "session.json" in the ".auth" directory.
Next, load the previously saved session storage in your specific test. Use fs.readFileSync() to do this:
const sessionStorage = JSON.parse(fs.readFileSync('playwright/.auth/session.json', 'utf-8'));
await context.addInitScript(storage => {
if (window.location.hostname === 'ray.run') {
for (const [key, value] of Object.entries(storage))
window.sessionStorage.setItem(key, value);
}
}, sessionStorage);
This code sets up a new context and its initial script to set each key-value pair from the loaded session storage into window.sessionStorage. Remember to replace 'ray.run' with your target domain.
By following these steps, you can handle any random modal that appears during testing.
If you still have questions, please ask a question and I will try to answer it.
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.